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?

2
  • 1
    interesting, running function in node terminal, results true twice. but running when saved into file show false twice Commented Mar 28, 2018 at 17:58
  • Didn't try in node terminal. Now it is even weirder :) Commented Mar 28, 2018 at 17:59

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.