Last active
October 2, 2015 03:35
-
-
Save kreja/64beb9c94d1267dececd to your computer and use it in GitHub Desktop.
利用 Object.defineProperty / Object.defineProperties 实现:改变一个属性影响另一个属性的值
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 改变长方形的高宽,面积也会自动改变 | |
*/ | |
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