0
const profile = {
    name: 'Alex',
    getName :() =>{
        return this.name;
    }
};

Here I am not getting the name as 'Alex'. But when I am using the function keyword instead, I am getting the desire result. Why?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    The arrow function is lexically bound in an object literal the context is *not* the object which is not created yet. – VLAZ Dec 17 '19 at 08:56
  • Does this answer your question? [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions) – VLAZ Dec 17 '19 at 09:01
  • Also relevant [How to bind 'this' to an object arrow function?](https://stackoverflow.com/questions/52113035/how-to-bind-this-to-an-object-arrow-function) [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – VLAZ Dec 17 '19 at 09:02

1 Answers1

0

this with Arrow Functions:

Significant advantage it offers is the fact that it does not bind its own this. In other words, the context inside arrow functions is lexically or statically defined.

if you are accessing method inside object you need to use regular function instead of arrow function.

const profile = {
    name: 'Alex',
    getName :function(){
        return this.name;
    }
};

For more clarification of this, you can visit this keyword

akhtarvahid
  • 9,445
  • 2
  • 26
  • 29