在许多已编译的 Javascript 模块中,序言中的某处都有一个Function('return this')()获取全局对象的调用。我正在一个解释器环境中工作,出于安全原因,禁止使用Function构造函数(以及)。eval我将上面的代码替换为(function(){return this})(),一切似乎都正常。
这是一个安全的替代吗?有没有失败的情况?为什么大多数已编译的 JS 模块更喜欢构造函数版本?
在严格模式下,您不会获得全局对象;你会得到undefined:
console.log( window === function(){
return (function(){return this})();
}() ); // true
console.log( window === function(){
"use strict";
return (function(){return this})();
}() ); // falseRun Code Online (Sandbox Code Playgroud)
Function 构造函数会转义严格模式,因此无论您是否已处于严格模式,您都会得到相同的结果:
console.log( window === function(){
return Function('return this')();
}() ); // true
console.log( window === function(){
"use strict";
return Function('return this')();
}() ); // trueRun Code Online (Sandbox Code Playgroud)