8

If you declare a class with a getter

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get fullName() {
    return [this.firstName, this.lastName].join(" ");
  }
}

you can access the getter after instantiating a new object

const person = new Person("Jane", "Doe");
console.log(person.fullName); // "Jane Doe"

but this won't work after copying the object using the spread operator

const personCopy = { ...person };
console.log(personCopy.fullName); // undefined

I think this is somewhat confusing syntax.

BassT
  • 819
  • 7
  • 22
  • So you answered your own question within a minute. – Faizan May 12 '19 at 09:55
  • Yes, I thought it was worth sharing. https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/ – BassT May 12 '19 at 09:57
  • @Faizan [Can I answer my own question?](https://stackoverflow.com/help/self-answer) – adiga May 12 '19 at 10:29
  • Well `personCopy` is a plain object, it doesn't inherit a getter from `Person.prototype`. Why would you still expect `.fullName` to work? – Bergi May 12 '19 at 12:15
  • @Bergi My point is that the syntax for two very different operations is identical and could lead to confusion. – BassT May 12 '19 at 15:25

2 Answers2

5

The spread operator only

copies own enumerable properties from a provided object onto a new object.

While the property defined using the get syntax

will be defined on the prototype of the object.

BassT
  • 819
  • 7
  • 22
3

The spread operator creates a new object using Object as the constructor. So, in your case, personCopy is not the instance of class Person and as a result of this, its __proto__ is not Person.prototype and therefore the getter won't work.

Kartik
  • 44
  • 3