Difference between window[] and eval() - Javascript

前端 未结 4 2029
滥情空心
滥情空心 2020-12-30 11:56

I\'ve been using both in javascript ... really don\'t know the difference. Googling always shows results for the \"window object\" or \"opening a new window in javascript\"

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 12:36

    Another point that has not been addressed is that eval will resolve the variable reference using the caller variable environment, for example:

    var foo = "global";
    
    (function () {
      var foo = "local";
      alert(eval("foo")); // alerts "local"
      alert(window["foo"]); // alerts "global"
    })();
    

    So as you can see, is not completely equivalent.

    If you simply want to reference a global variable, I would recommend you to use the window[prop] approach and avoid surprises.

提交回复
热议问题