I stumbled upon the function .globalEval()
from browsing the jQuery source. There is very brief documentation which I don't understand. Apparently, it is "important for loading external scripts dynamically". Why? The source is also somewhat obscure:
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
Do people actually use this in real life? If so, for what?
eval() is a Javascript built-in function. jQuery is a Javascript library, so it can use that function. It also provides $. globalEval() which behaves a little differently.
An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().
JavaScript eval() The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
It is used, as the name suggests, to execute the eval
code in the global context. For example, consider the following (jsFiddle):
function example(){
$.globalEval("var example1 = 'first';");
eval("var example2 = 'second';");
console.log("In function: " + example1); //Prints 'first'
console.log("In function: " + example2); //Prints 'second'
}
example();
console.log("Global: " + example1); //Prints 'first'
console.log("Global: " + example2); //ReferenceError
Because example1
was defined using globalEval
, it's in the global scope. Using plain old normal eval
, the variable is only availble in the scope in which eval
is called.
It can be useful if you want to load another JS script, and you want to execute that script in the global context (for example, above, we might need example1
to be available outside of the example
function, so we have to use globalEval
.
I'm not sure why the jQuery source uses window[ "eval" ].call
instead of just eval.call
, but I'm sure someone could explain :)
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