admin管理员组

文章数量:1394781

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.

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.

Share Improve this question asked May 12, 2019 at 9:45 BassTBassT 8498 silver badges23 bronze badges 6
  • So you answered your own question within a minute. – Faizan Commented May 12, 2019 at 9:55
  • Yes, I thought it was worth sharing. stackoverflow.blog/2011/07/01/… – BassT Commented May 12, 2019 at 9:57
  • @Faizan Can I answer my own question? – adiga Commented May 12, 2019 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 Commented May 12, 2019 at 12:15
  • @Bergi My point is that the syntax for two very different operations is identical and could lead to confusion. – BassT Commented May 12, 2019 at 15:25
 |  Show 1 more ment

2 Answers 2

Reset to default 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.

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.

本文标签: javascriptApplying spread operator on object with getterStack Overflow