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.

2 Answers

2
BassT On

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.

0
Kartik On

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.