我有一个 bar
类型的对象,它有一个由许多 foo
组成的数组。
我希望能够动态调用 foo
的方法 - 我可以通过传递字符串来使用 eval
来执行此操作,但我更愿意了解如何调用传递函数。
从概念上讲,我这样做的方式正确吗?
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
最佳答案
到处都是你泄漏的全局变量。
// 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");
关于javascript将对象方法传递给不同的对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5748055/