在新调用的函数中,`new Function("return this")()`的目的是什么?

Max*_*kyi 5 javascript

我正在检查setImmediate polyfill,它包含在立即调用函数中,具有以下内容:

(function (global, undefined) {
    "use strict";
...
}(new Function("return this")()));
Run Code Online (Sandbox Code Playgroud)

我对最后一个语句和传递给函数的参数的目的感到困惑.这个代码可以在浏览器和Node.js中运行吗?你能澄清一下吗?

Jam*_*rpe 10

编写代码使其可以访问全局范围,而无需知道包含该范围的对象是什么.例如,在浏览器中,全局范围是window,但在其他容器中则不是这样.

通过使用Function构造函数,您可以直接访问全局范围:

注意:使用Function构造函数创建的函数不会为其创建上下文创建闭包; 它们总是在全球范围内创建.运行它们时,它们只能访问自己的局部变量和全局变量,而不能访问调用Function构造函数的范围.这与使用eval和函数表达式的代码不同.

通过这样做:

(new Function("return this")())
Run Code Online (Sandbox Code Playgroud)

您可以在全局范围上创建和调用新函数,该函数返回全局范围.然后立即将其作为global对象传递给main函数.


Ori*_*iol 6

在非严格模式下,当调用函数而不设置this值时,它将成为全局对象:

10.4.3输入功能代码

  1. 如果函数代码是严格代码,请将ThisBinding设置为thisArg.
  2. 否则,如果thisArgnull未定义,则将ThisBinding设置为全局对象.

因此,this关键字可能是获取对全局对象的引用的方法:

this; // the global object
Run Code Online (Sandbox Code Playgroud)

第一个问题是this可以自定义(例如使用applycall):

(function() {
    this; // `123`, not the global object!
}).call(123);
Run Code Online (Sandbox Code Playgroud)

这可以使用自执行功能轻松修复:

// `this` may not be the global object here
(function() {
    this; // the global object
})();
Run Code Online (Sandbox Code Playgroud)

但是存在一个更严重的问题:this在严格模式下不会成为全局对象:

'use strict';
(function() {
    this; // `undefined`, not the global object!
})();
Run Code Online (Sandbox Code Playgroud)

要解决此问题,您可以使用函数构造函数.即使在严格模式下,默认情况下新函数也是非严格的.

'use strict';
(function() {
    new Function("return this")(); // the global object
})();
Run Code Online (Sandbox Code Playgroud)