-1
    const person = {
       name: John
       print: ()=> {
         console.log(this.name)
       } 
    }
    
    person.print()

The above will not print anything, as it'd say 'undefined' doesn't have any property name.

I read somewhere that arrow function use lexical scope to define 'this', and the object person doesn't create any lexical scope, hence 'this' is undefined.

My question is that why an Javascript object doesn't define any lexical scope? I'd have guessed that this refers to the object..


edit: I understand the difference between the normal function and arrow function. This is a very specific questions as in WHY the arrow function doesn't not work in an object due to the lexical scope.

I don't believe this is a dup

kakacii
  • 728
  • 3
  • 10
  • 24
  • 1
    It means `this` will be the same as `this` where you defined the object. You do want the behaviour of a normal `function`, not an arrow function. – deceze Dec 03 '22 at 15:56
  • For a more in-depth explanation of how `this` works in JavaScript, see [How does the "this" keyword work, and when should it be used?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work-and-when-should-it-be-used) Object literals don't have their own scope. (Which is why you also [can't directly access properties declared within the same object](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers).) (As for _why_: [because the language architects decided so](https://meta.stackoverflow.com/a/323382).) – Ivar Dec 05 '22 at 09:09
  • @Ivar finally someone reads my question! Thanks for the effort trying to answer the why. (and that's why this questions by itself is not a dup) – kakacii Dec 05 '22 at 12:36

1 Answers1

-3

You've used wrong syntax

const person = {
  name: 'John',
  print() {
    console.log(this.name)
  }
}

person.print()
Konrad
  • 21,590
  • 4
  • 28
  • 64