我有一个bar
类型的对象,它有一个包含许多foo
s的数组。
我希望能够动态地调用foo
的方法 - 我可以通过传递一个字符串来使用eval
来执行此操作,但我宁愿知道如何传递函数。< / p>
我是 - 从概念上讲 - 以正确的方式做到这一点?
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
答案 0 :(得分:2)
你到处都是泄漏的全球
// 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
要回答实际问题,请尝试此操作。
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");
答案 1 :(得分:0)
试试这个:
bar = function() {
var foos = [];
construct = function() {
foos[0] = new foo();
};construct();
this.callFoo = function(f) {
return foos[0][f].apply(foos[0]);
};
};