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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With