How to write this JavaScript code without eval?
var typeOfString = eval("typeof " + that.modules[modName].varName);
if (typeOfString !== "undefined") {
doSomething();
}
The thing is, the var name I want to check is on the line.
It may be simple, but I do not know how to do it.
Edit: Thanks for the very interesting answers. I will follow your suggestions and integrate them into my code, as well as conduct some testing and reporting. It may take some time.
Edit2: I had a different look at the T-shirt, and maybe it's better, I show you a big picture. I am grateful to the experts for explaining so beautifully that it is better with a lot of code:
MYNAMESPACE.Loader = ( function() {
function C() {
this.modules = {};
this.required = {};
this.waitCount = 0;
this.appendUrl = '';
this.docHead = document.getElementsByTagName('head')[0];
}
function insert() {
var that = this;
for (var modName in this.required) {
if(this.required.hasOwnProperty(modName)){
if (this.required[modName] === 'required') {
this.required[modName] = 'loading';
this.waitCount = this.waitCount + 1;
this.insertModule(modName);
}
}
}
this.intervalId = 0;
var checkFunction = function() {
if (that.waitCount === 0) {
clearInterval(that.intervalId);
that.onSuccess();
return;
}
for (var modName in that.required) {
if(that.required.hasOwnProperty(modName)){
if (that.required[modName] === 'loading') {
var typeOfString = eval("typeof " + that.modules[modName].varName);
if (typeOfString !== "undefined") {
that.required[modName] = 'ok';
that.waitCount = that.waitCount - 1;
if (that.waitCount === 0) {
clearInterval(that.intervalId);
that.onSuccess();
return;
}
}
}
}
}
};
this.intervalId = setInterval(checkFunction, 500);
}
C.prototype.insert = insert;
return C;
}());
var myLoader = new MYNAMESPACE.Loader();
myLoader.insert();
Edit3:
I plan to put this in the global namespace in the variable MYNAMESPACE.loadCheck, for simplicity, so the result will be, combined with various answers and comments:
if (MYNAMESPACE.loadCheck.modules[modName].varName in window) {
doSomething();
}
, Loader, "varName".