我在一个动态确定名称的对象上调用函数时遇到了一些问题。下面的代码说明了我的代码当前是如何设置的,我遇到的问题出现在名为doSomethingElse()的函数中。
var Obj = function(){
this.test = this.objMgr();
};
Obj.prototype.objMgr = function(){
var self = this;
function doSomething(){
//do some processing that seems unimportant to this particular prob
doSomethingElse();
}
function doSomethingElse(){
//The object that I need is determined at runtime, and is therefore dynamic
var callFuncOnThis = 'subObj';
//How the heck can I call function a on the object referenced in callFuncOnThis
this[callFuncOnThis].a(); //Doesn't work, this refers to dom window
self[callFuncOnThis].a(); //Doesn't work, self refers to obj
eval(callFuncOnThis).a(); //Works, but is there a better way?
}
var subObj = {
a:function(){
},
b:function(){
}
};
var subObj2 = {
a:function(){
},
b:function(){
}
};
doSomething();
return{
subObj:subObj,
subObj2:subObj2
}
};
var test = new Obj();
答案 0 :(得分:0)
subObj永远不会分配给您可以简单引用的范围。这就是为什么eval()是您最好的解决方案。话虽如此,我正在看一个奇怪的代码。你能详细说明一下吗?我觉得有一个架构问题。
此外,由于您要返回包含subObj和subObj2的对象,为什么不将其用作范围。
function doSomethingElse(){
// ...
retObj[callFuncOnThis].a()
}
var retObj = {'subObj': subObj, 'subObj2': subObj2};
doSomething();
return retObj;