用于虚拟人的getter\setter我一直在试着让自己的头脑清醒过来,但它并没有沉入其中。我读过JavaScript getter和Setters和定义getter和Setters只是不明白而已。有人能清楚地说:一个能手和策划者应该做什么,而且给出一些非常简单的例子?
3 回答
慕田峪4524236
TA贡献1875条经验 获得超5个赞
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];
}};fullNamefirstlast
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"
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
function Circle(radius) {
this.radius = radius;}Object.defineProperty(Circle.prototype, 'circumference', {
get: function() { return 2*Math.PI*this.radius; }});Object.defineProperty(Circle.prototype, 'area', {
get: function() { return Math.PI*this.radius*this.radius; }});c = new Circle(10);console.log(c.area);
// Should output 314.159console.log(c.circumference); // Should output 62.832添加回答
举报
0/150
提交
取消
