I’m having some issues calling a function on an object whose name is determined dynamically. The code below illustrates how my code is currently set up, and the problem that I’m having is occurring in the function called 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();
subObj is never assigned to a scope you can simply reference. That is why eval() is your best solution. Having said this, I’m looking at one weird bit of code. Can you elaborate on it a little? I feel like there is an architectural problem.
Also, since you’re returning an object that contains subObj and subObj2, why not use that as your scope.