Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: better way to add dynamic methods?

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();
like image 849
Geuis Avatar asked Nov 28 '22 00:11

Geuis


2 Answers

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"
like image 106
levik Avatar answered Nov 29 '22 13:11

levik


mhmh - I may be a bit late, but anyway:

new Function(argName1,...,argNameN, body)

for example:

x = new Function("y","return y*5");
x(3)

not much better than eval, though. (it's a pity, but strings are used as code-description, not something more structured as in LISP)

like image 27
blabla999 Avatar answered Nov 29 '22 14:11

blabla999