globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf( "use strict" ) === 1 ) {
script = document.createElement( "script" );
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
这个函数的功能是将变量转为全局变量,代码很简单
globalEval()
的功能我们可以理解为:
function test() {
// var ceval = eval;
eval('var a = 123');
alet(a);
}
test(); //123
但是如果代码稍微修改下,我们会有如下发现:
function test() {
eval('var a = 123');
// alet(a);
}
test();
alert(a); // Uncaught ReferenceError: a is not defined
这是为什么呢。但是唯一需要注意的小点是,eval()
既是关键字,又是window的属性。所以在test()
函数直接使用eval()
时,浏览器将它解析成了一个关键字,存储在函数内的临时作用域内,是个临时变量,所以会报错 。为了避免eval被当做关键字,可以将它初始化赋给一个变量,这个变量指向的是全局对象window,是window下的属性,这样就能正常工作了。代码如下
function test() {
var geval = eval;
geval('var a = 123');
}
test();
alert(test('a'));//123