getter和setter属性:
var p = { x:1.0, y:1.0, get r(){ return Math.sqrt(this.x*this.x + this.y * this.y); }, set r(newValue){ var oldValue = Math.sqrt(this.x*this.x + this.y * this.y); var ratio = newValue / oldValue; this.x *= ratio; this.y *= ratio; }, get theta(){ return Math.atan2(this.y,this.x); } }; console.log(p.r);//1.4142135623730951 console.log(p.x);//1 console.log(p.y);//1 console.log(p.theta);//0.7853981633974483 p.r = 10; console.log(p.r);//10 console.log(p.x);//7.071067811865475 console.log(p.y);//7.071067811865475 console.log(p.theta);//0.7853981633974483
r是可读写的存取属性,而theta是只读属性,它只有getter方法。和数据属性一样,存取属性是可以继承的。
存取器属性用于智能检测属性:
var serialnum = { $n : 0, get next(){return this.$n++}, set next(n){ if(n > this.$n) this.$n = n; else throw "序号的值不能比当前小"; } } console.log(serialnum.$n);//0 console.log(serialnum.next);//0 serialnum.next = 4; console.log(serialnum.$n);//0 console.log(serialnum.next);//4 serialnum.next = 3; console.log(serialnum.$n); console.log(serialnum.next);//Uncaught 序号的值不能比当前小