Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .globalEval() function

Tags:

jquery

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?

like image 739
Randomblue Avatar asked Oct 27 '11 20:10

Randomblue


People also ask

Does jQuery use eval?

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.

What can I use instead of eval in JavaScript?

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().

What is eval function in JavaScript?

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.


1 Answers

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 :)

like image 100
James Allardice Avatar answered Sep 30 '22 13:09

James Allardice