Javascript:添加动态方法的更好方法?

Geu*_*uis 4 javascript methods dynamic

我想知道是否有更好的方法将动态方法添加到现有对象.基本上,我试图动态组装新方法,然后将它们附加到现有函数.

这个演示代码有效.

builder = function(fn, methods){

    //method builder
    for(p in methods){
        method = 'fn.' + p + '=' + methods[p];
        eval(method);
    }

    return fn;
}
test = {}
test = builder(test, {'one':'function(){ alert("one"); }','two':'function(){ alert("two"); }'} );

test.one();
test.two();
Run Code Online (Sandbox Code Playgroud)

lev*_*vik 22

您不需要每次都评估它们.

您可以创建现有的函数对象,然后将它们作为属性分配给对象.

var methods = {
  'increment': function() { this.value++; },
  'display' : function() { alert(this.value); }
};

function addMethods(object, methods) {
  for (var name in methods) {
    object[name] = methods[name];
  }
};

var obj = { value: 3 };
addMethods(obj, methods);
obj.display();  // "3"
obj.increment();
obj.display();  // "4"
Run Code Online (Sandbox Code Playgroud)

然而,规范的,面向对象的方式是使用构造函数和原型,但这并不是真正动态的,因为您构造的每个对象都具有相同的方法:

function MyObj(value) {
  this.value = value;
};
MyObj.prototype.increment = function() {
  this.value++;
};
MyObj.prototype.display = function() {
  alert(this.value);
}
var obj = new MyObj(3);
obj.display();  // "3"
obj.increment();
obj.display();  // "4"
Run Code Online (Sandbox Code Playgroud)


bla*_*999 10

嗯 - 我可能有点晚了,但无论如何:

new Function(argName1,...,argNameN, body)
Run Code Online (Sandbox Code Playgroud)

例如:

x = new Function("y","return y*5");
x(3)
Run Code Online (Sandbox Code Playgroud)

但是并不比eval好多少.(很遗憾,但是字符串被用作代码描述,而不是像LISP那样更有条理的东西)


Mar*_*les 5

如果需要动态基于特定类型的对象...例如:

var logTypes = ["fatal", "error", "warning", "info", "trace", "debug", "profile"];
Run Code Online (Sandbox Code Playgroud)

然后你可以保留"this"对象输出的引用并在方法中使用它.

function CustomLogger () {

   var outter = this;

   // creating the logger methods for all the log types and levels
   _.each(logTypes, function (logType) {
        outter[logType] = function (msg) {
           console.log("[%s] %s", logType, msg);
        };
   });
}
Run Code Online (Sandbox Code Playgroud)

这样,您就可以获得新的动态方法......

var logger = new CustomLogger();
logger.info("Super cool!");
Run Code Online (Sandbox Code Playgroud)

这将输出以下内容:

"[info] Super cool!"
Run Code Online (Sandbox Code Playgroud)