0

why adding a property to globalThis inside a function doesn't work?

let foo = function(){
    this.name='Global Elite'
}
foo()
console.log(this.name) // undefined

This gets more confusing because if I use the arrow function instead the function keyword it can add the name property to global object.

let foo = ()=>{
    this.name='Global Elite'
}
foo()
console.log(this.name) // Global Elite

Edit: I ran the above code in node js.

  • cannot reproduce, also note, that this would throw in strict mode. – ASDFGerte Feb 03 '22 at 20:34
  • Edited your post to actually run your script. It doesn't behave as you described. Please update the example. – Ruan Mendes Feb 03 '22 at 20:41
  • Can reproduce when ran on Node.js. – Ivar Feb 03 '22 at 20:42
  • This is not really a duplicate unless we understand what the OP is asking, since the behavior they describe seems impossible. – Ruan Mendes Feb 03 '22 at 20:44
  • 1
    like @Ivar posted, [understanding This](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) `Arrow functions don’t have their own this […] binding. Instead, [this identifier is] resolved in the lexical scope like any other variable. That means that inside an arrow function, this [refers] to the [value of this] in the environment the arrow function is defined in (i.e. “outside” the arrow function).` – knicholas Feb 03 '22 at 20:44
  • @knicholas Thanks, I understood that the arrow function have their own 'this', so its resolved in the lexical scope. But but i don't understand why this outside any function refers to an empty object where as in the node interpreter 'this' refers to the global object. – Himanshu Bharti Feb 03 '22 at 21:32
  • @HimanshuBharti I believe that is because node uses modules and `The GetThisBinding concrete method of a module Environment Record […] [does this]: Return undefined.` – knicholas Feb 03 '22 at 21:36
  • The "why" can be answered with "because the specifications says so". ASDFGerte posted a link earlier pointing to [this Q/A](https://stackoverflow.com/questions/22770299/meaning-of-this-in-node-js-modules-and-functions), which basically states your findings as facts. – Ivar Feb 03 '22 at 21:40

0 Answers0