Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding of `this` in a setTimeout() callback in Node.js

In Node.js, inside a callback passed to setTimeout(), this seems to be bound to the timeoutObject returned by setTimeout() itself (both in strict mode and in non strict 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 is bound (as I would expect) to the global object window (or is undefined, in strict mode).

The documentation doesn't say anything about this non-standard behaviour.

Why is this?

like image 821
kYuZz Avatar asked Oct 31 '22 10:10

kYuZz


1 Answers

Nodejs is not browser. "Standards" what you are talking about are for browsers. Read the docs:

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

To implement these 2 timing functions "this" should be binded to window object (not available in Nodejs) or worker object (not available in nodejs).

Nodejs has it's own global object, that might be good target in this case, but I think it's better to have this binded to this function, not some global object. Seems like developers from Nodejs thinks that way too.

It's not against the "standards" because standards has nothing about such environment, where window, navigation, location objects are not present.

like image 193
Lukas Liesis Avatar answered Nov 11 '22 21:11

Lukas Liesis