What is the purpose of `new Function (" return this ") ()` in the immediately called function

I look through the setImmediate polyfill and end the function inside the immediate call as follows:

(function (global, undefined) {
    "use strict";
...
}(new Function("return this")()));

I am confused about the purpose of the last statement and the parameters passed to the function. Does he have something to do so that this code can run both inside the browser and on Node.js? Can you clarify?

+3
source share
2 answers

The code is written in such a way that it has access to the global area, not knowing what an object containing this area is. For example, the browser has a global scope window, but in other containers this is not so.

, :

. , Function, ; . , Function. eval .

:

(new Function("return this")())

, . global.

+7

, this, :

10.4.3

, this :

this; // the global object

, this (, apply call):

(function() {
    this; // `123`, not the global object!
}).call(123);

:

// `this` may not be the global object here
(function() {
    this; // the global object
})();

: this :

'use strict';
(function() {
    this; // `undefined`, not the global object!
})();

, . .

'use strict';
(function() {
    new Function("return this")(); // the global object
})();
+5

Source: https://habr.com/ru/post/1695182/


All Articles