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?
It is used, as the name suggests, to execute the
evalcode in the global context. For example, consider the following (jsFiddle):Because
example1was defined usingglobalEval, it’s in the global scope. Using plain old normaleval, the variable is only availble in the scope in whichevalis 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
example1to be available outside of theexamplefunction, so we have to useglobalEval.I’m not sure why the jQuery source uses
window[ "eval" ].callinstead of justeval.call, but I’m sure someone could explain 🙂