Reputation: 1295
The following function provides two different results, in Node and Browser:
(function funfunfun(root, factory) {
console.log(root === this);
factory(root);
})(this, function (root) {
console.log(root === this);
});
In node, it will output false twice. In the browser it will output true twice, as I would expect.
So the question is... why?
Upvotes: 3
Views: 285
Reputation: 10997
In a browser, within an unbound function, this
will point to window object. Thats why you are getting two trues in browser.
Now in nodejs equalent of window is global
. If you run this===global
you will get true in repl.
But from file this is not equal to global
.
global variable assignment in node from script vs command line
Upvotes: 5
Reputation: 4956
This might already be known, but just wanted to add to @Subin's answer that if you explicitly bind the functions to the same this, it will return true whether inside script or REPL.
(function funfunfun(root, factory) {
console.log(root === this);
factory(root);
}).call(this, this, (function (root) {
console.log(root === this);
}).bind(this, this));
Also, this answer provides good info on the global object.
Upvotes: 2