Skip to content

Instantly share code, notes, and snippets.

@kreja
Last active October 2, 2015 03:35
Show Gist options
  • Save kreja/64beb9c94d1267dececd to your computer and use it in GitHub Desktop.
Save kreja/64beb9c94d1267dececd to your computer and use it in GitHub Desktop.
利用 Object.defineProperty / Object.defineProperties 实现:改变一个属性影响另一个属性的值
var rectangle = {
_h: 1,
_w: 1,
_area: 1
};
Object.defineProperties(rectangle,{
h: {
get: function(){
return this._h;
},
set: function(newValue){
this._h = newValue;
this._area = this._w * this._h;
}
},
w: {
get: function(){
return this._w;
},
set: function(newValue){
this._w = newValue;
this._area = this._w * this._h;
}
},
area: {
get: function(){
return this._area;
},
set: function(){
alert('You can\'t set area!');
}
}
});
rectangle.h = 2;
rectangle.w = 2;
rectangle.area = 5;
console.log(rectangle.area);
/*
* 改变长方形的高宽,面积也会自动改变
*/
var rectangle = {
_h: 1,
_w: 2,
_area: 2
};
Object.defineProperty(rectangle, 'h',{
get: function(){
return this._h;
},
set: function(newValue){
this._h = newValue;
this._area = this._w * this._h;
}
});
Object.defineProperty(rectangle, 'w',{
get: function(){
return this._w;
},
set: function(newValue){
this._w = newValue;
this._area = this._w * this._h;
}
});
Object.defineProperty(rectangle, 'area',{
get: function(){
return this._area;
},
set: function(){
alert('You can\'t set area!');
}
});
rectangle.h = 2;
rectangle.w = 2;
rectangle.area = 5;
console.log(rectangle.area);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment