[Core Javascirpt] Basic Metaprogramming: Dynamic Method

Somehow it looks like reflect in Java.

For example: We define an mothod on the Object, it called defineMethod(). It accepts two arguements, one is methodName andother is methodBody. 

Read More: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Using defineProperty() method of Object object to create method.

Object.prototype.defineMethod = function(methodName, methodBody){
  
  Object.defineProperty(this, methodName, {
    enumerable: true,
    configurable: true,
    value: methodBody
  });
}


var dog = {breed: "Shelty"};
dog.defineMethod("bark", function(){
  return "Woof!";
});
console.log(dog.breed);
console.log(dog.bark());


//"Shelty"
//"Woof!"

 

More useful case:

function User(){
  
  User.statuses = ["inactive", "active"];
  _.each(User.statuses, function(status){
    this.defineMethod("is"+status.capitalize(), function(){
      return this.status == status;
    })
  }, this);
}


var user = new User();
user.status = "active";

console.log(user.isActive());
console.log(user.isInactive());

//isActive() and isInactive() methods are created dynamcally during the running time.

Library: lodash  and active-support.js

Read more: https://github.com/brettshollenberger/ActiveSupport.js/tree/master

https://egghead.io/lessons/core-javascript-basic-metaprogramming-dynamic-method

posted @ 2016-05-02 03:06  Zhentiw  阅读(376)  评论(0编辑  收藏  举报