Binding `this` in the setTimeout () callback in Node.js

In Node.js, inside the callback passed to setTimeout() , this appears to be tied to the timeoutObject returned by setTimeout() (both in strict mode and non-line mode!):

 var timeoutObject = setTimeout(function () { console.log(this === timeoutObject); // true }, 0); var timeoutObject = setTimeout(function () { 'use strict'; console.log(this === timeoutObject); // true }, 0); 

This is not the case in the browser, where this tied (as one would expect) to the global window object (or is undefined , in strict mode).

The documentation says nothing about this non-standard behavior.

Why is this?

+5
source share
2 answers

Here is one discussion of this` binding incorrect for `setTimeouf(..)` and `setInterval(..) . Which explains the question, there was even an attempt to correct it, which was not accepted.

Here are some ideas as shown below.

setTimeout associates the timer object with the this object in the callback. First of all, in most cases, the Node runtime is a β€œmodule”, so when

 var k=2; exports.k=3; console.log(k);//2 console.log(this.k);//3 

This is the difference between a browser and a node. Linking to a windowed object in a browser is easy because it is a global object. But in Node, setTimeout / setInterval cannot get the export object or module runtime.


Regardless of whether there are advantages in the current method * *, it works (although it is provided without documents, but it is used in the wild). For instance:

 setInterval(function() { if (/* <condition> */) this.unref(); // do more stuff }, /* <n> */); 
+1
source

Nodejs is not a browser. "Standards" what you say for browsers. Read the docs:

https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowtimers-settimeout

To implement these two synchronization functions, β€œthis” must be bound to a window object (not available in Nodejs) or a work object (not available in nodejs).

Nodejs has its own global object, which may be a good target in this case, but I believe that it is better to bind this function to this function, and not to some global object. Nodejs developers seem to think so too.

This is not against "standards", because standards have nothing about an environment where there are no window objects, navigation, or location.

+1
source

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


All Articles