Javascript:更好的方式添加动态方法? [英] Javascript: better way to add dynamic methods?
问题描述
我想知道是否有更好的方式将动态方法添加到现有对象。基本上,我试图动态地组合新的方法,然后将它们附加到现有的函数。
这个演示代码可以工作。
{pre>
builder = function(fn,methods){
//方法构建器
for(p in methods){
method ='fn。'+ p +'='+ methods [p];
eval(method);
}
return fn;
}
test = {}
test = builder(test,{'one':'function(){alert(one);}','two' ){alert(two);}'});
test.one();
test.two();
你不需要每次评估它们。
您可以创建现有的功能对象,然后将其分配给对象的属性。
code> var methods = {
'increment':function(){this.value ++; },
'display':function(){alert(this.value); }
};
函数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
然而,规范的面向对象的方法是使用构造函数和原型,但是这并不是真正的动态的,因为您构建的每个对象将具有相同的方法:
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
I'm wondering if there's a better way to add dynamic methods to an existing object. Basically, I am trying to assemble new methods dynamically and then append them to an existing function.
This demo code works.
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();
You don't need to eval them each time.
You can create existing function objects, then assign them as properties to your objects.
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"
The canonical, object-oriented way however, is to use constructors and prototypes, but this isn't really dynamic in that each object you construct will have the same methods:
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"
这篇关于Javascript:更好的方式添加动态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!