<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
//2、访问器属性
//[[Configurable]],[[Enumerable]],[[Get]],[[Set]]
//访问器属性不能直接定义,必须使用Object.definePropertye()来定义
var book = {
_year: 2004,
edition: 1
};
Object.defineProperty(book , 'year' , {
get: function(){
return this._year;
},
set: function(newValue){
if(newValue > 2004){
this._year = newValue;
this.edition += newValue - 2004;
}
}
});
book.year = 2008;
alert(book.edition);
//这是访问器属性常见的方式,即设置一个属性的值导致其他属性发生变化。
</script>
</body>
</html>
提取js部分
//2、访问器属性
//[[Configurable]],[[Enumerable]],[[Get]],[[Set]]
//访问器属性不能直接定义,必须使用Object.definePropertye()来定义
var book = {
_year: 2004,
edition: 1
};
Object.defineProperty(book , 'year' , {
get: function(){
return this._year;
},
set: function(newValue){
if(newValue > 2004){
this._year = newValue;
this.edition += newValue - 2004;
}
}
});
book.year = 2008;
alert(book.edition);
//这是访问器属性常见的方式,即设置一个属性的值导致其他属性发生变化。