1

In the browser, this in classic and arrow functions expectedly returns the Windows object:

<script>
    function testClassic() {
        console.log(this);
    }
    const testArrow = () => {
        console.log(this);
    }
    testClassic();
    testArrow();
</script>

enter image description here

But in Node, this is the global object only in the classic function but this is empty in the arrow notation function. Why is that?

enter image description here

Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047
  • 1
    Does this answer your question? [Meaning of "this" in node.js modules and functions](https://stackoverflow.com/questions/22770299/meaning-of-this-in-node-js-modules-and-functions) – Dave Newton Jun 24 '21 at 14:19
  • https://stackoverflow.com/questions/12682514/nodejs-this-empty-object – Dilshan Jun 24 '21 at 14:27
  • @DaveNewton Not really because it doesn't address the difference between `this` in classic functions and arrow functions as I showed above have different values. – Edward Tanguay Jun 24 '21 at 14:27
  • Yes, because `this` is late-bound in JS. The arrow function forces a binding at declaration, so it’s the module; the `function`’s `this` is bound at execution time, so will be the global object. NodeJS module-izes the file. – Dave Newton Jun 24 '21 at 14:31
  • @Dilshan The question stackoverflow.com/questions/12682514/nodejs-this-empty-object explains why `this` in Node is empty but my question is more about the different values of `this` in these various contexts, i.e. why do classic and arrow functions both give the same value in the browser, but in Node, classic functions have the global object. – Edward Tanguay Jun 24 '21 at 14:33
  • My comment explains that; the dupe goes into the details regarding "this" as it pertains to modules. AFAICT the confusion here is not knowing that when you run a file in Node that file is a module. – Dave Newton Jun 24 '21 at 15:14
  • I think this answer your question. [The 'this' keyword behaves differently in Nodejs and browser](https://stackoverflow.com/a/34838985/6425710) – Dr.G Jul 03 '22 at 03:31

0 Answers0