How To Write This JavaScript Code Without Eval?
How to write this JavaScript code without eval? var typeOfString = eval('typeof ' + that.modules[modName].varName); if (typeOfString !== 'undefined') { doSomething(); } The poin
Solution 1:
in JS every variable is a property, if you have no idea whose property it is, it's a window
property, so I suppose, in your case, this could work:
var typeOFString = typeof window[that.modules[modName].varName]
if (typeOFString !== "undefined") {
doSomething();
}
Solution 2:
Since you are only testing for the existence of the item, you can use in
rather than typeof
.
So for global variables as per ZJR's answer, you can look for them on the window
object:
if (that.modules[modName].varName in window) {
...
}
If you need to look for local variables there's no way to do that without eval
. But this would be a sign of a serious misdesign further up the line.
Post a Comment for "How To Write This JavaScript Code Without Eval?"