我一直在尝试了解 getter 和 setter,但没有深入理解。我读过 JavaScript Getters and Setters和 Defining Getters and Setters只是没有得到它。
有人可以清楚地说明:
- getter 和 setter 的用途,以及
- 举一些非常简单的例子?
最佳答案
除了 @millimoose's answer ,setter 也可用于更新其他值。
function Name(first, last) {
this.first = first;
this.last = last;
}
Name.prototype = {
get fullName() {
return this.first + " " + this.last;
},
set fullName(name) {
var names = name.split(" ");
this.first = names[0];
this.last = names[1];
}
};
现在,您可以设置fullName
,first
和last
将被更新,反之亦然。
n = new Name('Claude', 'Monet')
n.first # "Claude"
n.last # "Monet"
n.fullName # "Claude Monet"
n.fullName = "Gustav Klimt"
n.first # "Gustav"
n.last # "Klimt"
关于javascript - 傻瓜的 Getter\setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33002538/