如何为已经定义的 JavaScript 对象定义 getter 属性?
考虑以下代码:
// Creating an empty object, without inheriting (binding) to any prototype
var human = Object.create(null);
human.firstName = 'Saeed';
human.lastName = 'Neamati';
现在,我想向该对象添加一个 fullName
属性,该属性返回该对象的 firstName + ' ' + lastName
。
使用对象文字表示法,我可以简单地以这种方式编写 getter 函数:
var human = {
firstName: 'Saeed',
lastName: 'Neamati',
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
但我无法弄清楚如何将 getter 属性附加到已经在其他地方构建的对象。
Consider this code:
// Creating an empty object, without inheriting (binding) to any prototype
var human = Object.create(null);
human.firstName = 'Saeed';
human.lastName = 'Neamati';
Now, I want to add a fullName
property to this object, which returns the firstName + ' ' + lastName
of the object.
Using object literal notation, I can simply write a getter function this way:
var human = {
firstName: 'Saeed',
lastName: 'Neamati',
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
But I can't figure out how to attach a getter property to an object, which is already built somewhere else.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 Object.defineProperty
其中
;
可以是这样的:You can use Object.defineProperty
Where
<descriptor>
can be something like:试试这个:
希望有帮助:)
try this :
Hope it helps :)