2

I guess this in immediately-invoking functions always refers to the global/window object in javascript, i.e. the result should be true in both nodejs and browser shown below. But this is not the case, I got a false in nodejs, why? The code is completely the same.

main.js

var global = this;
(function () {
    console.log(global === this); // false
})();

index.html

<html>
  <head></head>
  <body>
    <script>
      var global = this;
      (function () {
          console.log(global === this); // true
      })();
    </script>
  </body>
</html>
Searene
  • 25,920
  • 39
  • 129
  • 186
  • 1
    Did you try `console.log(this)`? – le_m May 30 '17 at 14:32
  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this – Scott Marcus May 30 '17 at 14:33
  • Here's a more direct link. Basically the behavior you're seeing in the browser is deprecated and does not work in strict mode. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Securing_JavaScript – Patrick McElhaney May 30 '17 at 14:38
  • If this is a topic you want to know more about, I found this extremely helpful myself https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md – dgeare May 30 '17 at 14:41

0 Answers0