I am trying to create an example that demonstrates why the idiom var that = this
is necessary (e.g. as described here).
So, I started with an example of erroneous code that would fail to properly bind this
. However, the code I wrote gave me some unexpected results (in another direction):
message = "message in global scope";
// the below erroneous code aims to demonstrate why we need
// the "var that = this" idiom to capture the "this" lexical scope
var createLoggingFunctionWrongWay = function () {
return function () {
console.log(this.message);
};
};
// the below *does* print "message in global scope"
// i.e. fails in the way I expected
createLoggingFunctionWrongWay.call({message:"message"})();
// I was expecting the below to also print "message in global scope" as
// well, yet it prints "undefined"
setTimeout(createLoggingFunctionWrongWay.call({
message: "message"
}), 1000);
When running under nodejs
I get:
$ nodejs foo.js
message in global scope
undefined
My question is why doesn't the second call (that uses setTimeout
) also fail in the same way and interpret this
to point to the global
object in Node.js
(where the message
variable resides)?
update
When I inserted a console.log(this)
inside the anonymous function, on the first invocation I get the global context object (where message
resides), whereas on the second invocation (via the setTimeout
) I get the following object:
{ _idleTimeout: 1000,
_idlePrev: null,
_idleNext: null,
_idleStart: 1446483586705,
_onTimeout: [Function],
_repeat: false
}