如何在没有eval的情况下编写此JavaScript代码?

时间:2010-04-08 13:55:54

标签: javascript eval

如何在没有eval的情况下编写此JavaScript代码?

var typeOfString = eval("typeof " + that.modules[modName].varName);
if (typeOfString !== "undefined") {
  doSomething();
}

关键是我要检查的var的名称是字符串。

也许这很简单,但我不知道如何。

编辑:感谢您到目前为止非常有趣的答案。我会按照您的建议将其集成到我的代码中并进行一些测试和报告。可能需要一段时间。

Edit2:我又看了一眼可能,也许我会向你展示更大的图片。我很高兴专家解释如此美丽,用更多代码更好:

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;
    //insert all script tags to the head now!
    //loop over all modules:
    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);
        }
      }
    }

    //now poll until everything is loaded or 
    //until timout

    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") {
              //module is loaded!
              that.required[modName] = 'ok';
              that.waitCount = that.waitCount - 1; 
              if (that.waitCount === 0) {
                clearInterval(that.intervalId);
                that.onSuccess();
                return;
              }
            }
          }
        }
      }
    };

    //execute the function twice a second to check if all is loaded:
    this.intervalId = setInterval(checkFunction, 500);
    //further execution will be in checkFunction,
    //so nothing left to do here
  }
  C.prototype.insert = insert;

  //there are more functions here...

  return C;
}());


var myLoader = new MYNAMESPACE.Loader();

//some more lines here... 

myLoader.insert();

EDIT3:

为了简单起见,我打算将它放在变量MYNAMESPACE.loadCheck的全局命名空间中,所以结果将是,结合不同的答案和注释:

if (MYNAMESPACE.loadCheck.modules[modName].varName in window) {
  doSomething();
}

当然,我必须更新Loader类,其中提到了“varName”。

2 个答案:

答案 0 :(得分:3)

在JS中,每个变量都是一个属性,如果你不知道它的属性是什么,它就是window属性,所以我想,在你的情况下,这可能有用:

var typeOFString = typeof window[that.modules[modName].varName]
if (typeOFString !== "undefined") {
  doSomething();
}

答案 1 :(得分:1)

由于您只测试商品的存在,因此您可以使用in而不是typeof

因此,根据ZJR的答案,对于全局变量,您可以在window对象上查找它们:

if (that.modules[modName].varName in window) {
    ...
}

如果你需要寻找局部变量,没有eval就没有办法做到这一点。但这将是一个严重错误设计的标志。

相关问题