Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  43] [ 7]  / answers: 1 / hits: 32761  / 15 Years ago, wed, february 25, 2009, 12:00:00

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();

More From » dynamic

 Answers
23

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

[#99933] Tuesday, February 17, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chyanne

Total Points: 208
Total Questions: 120
Total Answers: 110

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
chyanne questions
Mon, Aug 16, 21, 00:00, 3 Years ago
Fri, Jul 16, 21, 00:00, 3 Years ago
Tue, Jun 29, 21, 00:00, 3 Years ago
Mon, Sep 7, 20, 00:00, 4 Years ago
Mon, Jul 6, 20, 00:00, 4 Years ago
;