Difference between window[] and eval() - Javascript

前端 未结 4 2005
滥情空心
滥情空心 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:31

    eval() interprets arbitrary javascript statements, whereas with window you are accessing a property of the window object.

    In your example, you seem to be using a property name in both eval() and window[]. As the global scope in a browser is the same as the window object's scope they will evaluate to the same thing.

    You can think of your eval("v"+e) statement as being equivalent to eval("window['v'" + e +" ]").

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 12:40

    "v"+e -> string

    eval(x) -> evaluates the string x, containing javascript expression

    window[x] -> returns window's property with the same name, as tha value of x is. this in fact can be a global variable

    therefore, when you have a global variable v1 = "foo", and e = 1, then eval("v"+e) and window["v" + e] both return "foo"

    0 讨论(0)
  • 2020-12-30 12:43

    Both return a global variable's value. The difference is that if the global variable is undefined, you will get an error on executing eval() whereas window['variableName'] will return undefined(not an error) because accessing an undefined property is not an error but accessing an undefined variable is an error.

    0 讨论(0)
提交回复
热议问题