Reputation: 3347
I am learning about .bind() from the example on MDN here, the only changes that I've made to this example is where I added the console.log()'s.
this.x = 9; // this refers to global "window" object here in the browser
var module = {
x: 81,
getX: function() { return this.x; }
};
console.log(module.getX()); // 81
var retrieveX = module.getX;
console.log(retrieveX());
// returns 9 - The function gets invoked at the global scope
// Create a new function with 'this' bound to module
// New programmers might confuse the
// global var x with module's property x
var boundGetX = retrieveX.bind(module);
console.log(boundGetX()); // 81
Running this using Node I get,
$ node bind.js
81
undefined
81
The 'undefined' output should be '9'.
Why am I not getting that output?
Here's a screenshot from my attempt with Node:
Upvotes: 2
Views: 89
Reputation: 1075039
Running this using Node I get...
Because in NodeJS, your seemingly-top-level code isn't running at global scope and in it, this
doesn't refer to the global object. All NodeJS code runs within a NodeJS module, which is not global scope. Since this
doesn't refer to the global object, this.x = 9;
doesn't create a property called x
on it, and so when the unbound function is run with the wrong this
(with this
referring to the global object), it gets undefined
instead of 9
for this.x
property since there is no global property called x
.
If you ran that code in a browser, it would do what MDN says it does. Alternately, you can change this.x = 9;
to global.x = 9;
and it will on NodeJS as well, because in NodeJS, global
is a reference to the global object (just like this
at global scope in browsers, and just like the window
identifier in browsers).
You'll find that a lot of code examples which assume they're run at global scope will behave slightly differently when run in NodeJS, for this very reason. For instance, var n;
at global scope creates a property on the global object, but var n;
at the top-level of a NodeJS module just creates a variable scoped to that module, not a global.
Upvotes: 4