3

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?

Raanan W
  • 1,127
  • 5
  • 18

2 Answers2

5

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

Subin Sebastian
  • 10,367
  • 3
  • 35
  • 41
  • Your answer is correct, i dont know why someone downvote it. `Simply because every node module is wrapped in an IIFE of sorts, so by default you are not in the global scope.` – Artur P. Mar 28 '18 at 18:12
  • I have no idea why the down vote as well (certainly not from me :) ). So what it means is that the function is executed in a different scope than the one it was executed from? Interesting. You learn something new every day. – Raanan W Mar 28 '18 at 18:13
2

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.

Vasan
  • 4,438
  • 3
  • 17
  • 38