Reputation: 7332
I have an object of type bar
which has an Array of many foo
s.
I want to be able to call a method of foo
dynamically - I could do this with eval
by passing a string, but I would rather get a handle on how to pass the function.
Am I - conceptually - doing this the right way?
var foo = function() {
this.methodA = function() {
return "a";
};
this.methodB = function() {
return "b";
};
};
var bar = function() {
var foos = [];
this.construct = function() {
foos[0] = new foo();
}; this.construct();
this.callFoo = function(f) {
return foos[0].f();
};
};
b = new bar();
b.callFoo(foo.methodA); //<-- This doesn't work
b.callFoo(methodA); //<-- Or this
Upvotes: 0
Views: 589
Reputation: 169383
your leaking globals everywhere.
// global leak
foo = function() {
// global leak
methodA = function() {
return "a";
};
// global leak
methodB = function() {
return "b";
};
};
// global leak
bar = function() {
var foos = [];
// global leak
construct = function() {
foos[0] = new foo();
};construct();
this.callFoo = function(f) {
return foos[0].f();
};
};
b = new bar();
b.callFoo(foo.methodA); //<-- This doesn't work
b.callFoo(methodA); //<-- Or this
To answer the actual question try this.
var foo = function() {
return {
methodA: function() { return "a"; },
methodB: function() { return "b"; }
};
}
var bar = function() {
var foos = [];
return {
construct: function() {
foos.push(foo());
},
callFoo = function(name) {
return foos[0][name]();
}
}
}
b = bar();
b.callFoo("methodA");
Upvotes: 2
Reputation: 146302
try this:
bar = function() {
var foos = [];
construct = function() {
foos[0] = new foo();
};construct();
this.callFoo = function(f) {
return foos[0][f].apply(foos[0]);
};
};
Upvotes: 0