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 fromPerson.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
2 Answers
Reset to default 5The 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
版权声明:本文标题:javascript - Applying spread operator on object with getter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744101611a2590896.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论