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" so couldn't find anything there.
eval("v"+e)
window["v"+e]
Sometimes window works for me and at other times eval works ....
So what's the difference between eval() and window[] ?
Sorry for the newbie question though !
Norman
The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of javascript. The javascript objects are string, array, date etc.
`Function() is a faster and more secure alternative to eval().
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.
The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2. If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function.
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.
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 +" ]")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With