0

I have the following code

const name = 'Jordan'

const myObj = {
  getName: function() {
    return this.name
  },
  getNameAnonymous: () => {
    return this.name
  }

}

console.log(myObj.getName())
console.log(myObj.getNameAnonymous())

When running, getName returns undefined and getNameAnonymous returns "result" (when I run it in JSFiddle but when I run it with Node I get undefined)

From what I understand this inside of arrow functions inside of objects is bound to the parent scope, so why doesn't getNameAnonymous return Jordan? And why does getName return undefined instead of a ReferenceError?

Jordan Baron
  • 141
  • 1
  • 12
  • 4
    In browser environment a top level `var` becomes a property of `window` but that is not true for a `const`. In no environment will you access that const using `this`. It would help if you explained what you are wanting to accomplish here – charlietfl Jun 26 '21 at 19:37
  • 1
    Also worth noting that `window` has a default `name` property that is empty string but is also assignable. It seems that jsfiddle is assigning the name of the iframe output page window as "result" – charlietfl Jun 26 '21 at 19:46
  • Ohhh. I see. So, because in the case of the arrow function `this` is bound to the `global` object, `name` is undefined because const variables do not get attached to the `global` object (`global` being `window` in the browser) – Jordan Baron Jun 26 '21 at 19:52
  • Yes and in browser case the window global actually has a `name` property. In jsfiddle run `console.log(window.name)` and it outputs `"result"` – charlietfl Jun 26 '21 at 20:08
  • This is a bit off topic, but how come I can do `window.fhjdgjfdgjhfd` and it will be undefined instead of throwing a ReferenceError? – Jordan Baron Jun 26 '21 at 20:10
  • Javascript doesn't error on properties of an actual object that don't exist. Note that if you open console on this page and log `wiindow.name` it is not undefined but rather an empty string – charlietfl Jun 26 '21 at 20:12

0 Answers0