0

How can we get the properties of post object to be available in getFullName function. I know if we can use function declaration intead of arrow function then 'this' will refer to the post object properties. But I was just wondering if we can achieve it using arrow function.

const post = {
  firstname: 'temp',
  lastname: 'code',
  getFullName: () => {
    return this.firstname + ' ' + this.lastname;
  }
}
Aditya
  • 78
  • 1
  • 6
  • 1
    Use a regular function expression instead, use arrow functions when it makes sense, don't try to put them everywhere just because. – goto Jan 18 '21 at 14:55
  • Or use a [getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) in the object: `get FullName() { return this.firstname + ' ' + this.lastname }` and access it with just `post.FullName` – adiga Jan 18 '21 at 14:57
  • @goto1, yes I understand it was just a question if it is possible using arrow function and this. I do understand the other ways to achieve this. – Aditya Jan 19 '21 at 15:51

1 Answers1

0

You could reference the post object it self.

const post = {
  firstname: 'temp',
  lastname: 'code',
  getFullName: () => {
    return post.firstname + ' ' + post.lastname;
  }
}

console.log(post.getFullName());
Olian04
  • 6,480
  • 2
  • 27
  • 54