0

running the same code in different environments produces different results1

try running the code below in chrome console and on node js, the first produces snehal snehal and the other undefined undefined

this.name = "snehal";

function meme() {
  console.log(this.name);
  function mem() {
    console.log(this.name);
  }
  mem();
}

meme(); 

The basic idea about this in JavaScript is that it points/refers to the object that contains it, so in the chrome console we can expect the inner mem function this to be === to the meme function this, but the same is not consistent in the node environment.

  • `this` refers to the object that contains the function means that the function `obj.foo = function () { console.log(this) }` will print `String(obj)`. By default, every function is attached to the global object which is `window` in the browser and `global` in NodeJs. In both cases `this.name = "shehal"` should result in attaching the property `name` to the global object and `this.name` inside the two function should return "shehal". Strange! Can you provide more context for the browser code? – Marcello Del Buono Oct 24 '21 at 20:36
  • 1
    _“`this` […] points/refers to the object that contains [the function]”_ is wrong. See [How does the "this" keyword work?](/q/3127429/4642212). @MarcelloDelBuono `console.log` does not invoke `String` or any `toString` method. The duplicate link has been edited. This behavior has already been explained. The reason is that `this` isn’t `global` in the top scope of a Node.js module. Apart from that, e.g. in functions called without base reference, or by simply using `globalThis` instead, it is. – Sebastian Simon Oct 24 '21 at 20:49

0 Answers0