87,993
社区成员
发帖
与我相关
我的任务
分享
<!DOCTYPE html>
<html>
<head>
<title>Multiple Properties Example</title>
<script type="text/javascript">
var book = {};
Object.defineProperties(book, {
_year: {
value: 2004
},
edition: {
value: 1
},
year: {
get: function(){
return this._year;
},
set: function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
}
});
book.year = 2005;
console.dir(book);
alert(book.edition); //2
</script>
</head>
<body>
<p>Note: this example only works in browsers that have implemented the ECMAScript 5 <code>Object.defineProperty()</code> method (IE9 and Firefox 4).</p>
</body>
</html>
。
var book = {
_year:2004,
edition:1,
get year(){
return this._year;
},
set year(newval){
this._year = newval;
this.edition += newval-2004;
}
}
book.year = 2005;
alert(book.edition)
const book = {
_year: 2004,
edition: 1,
get year() {
return this._year
},
set year(newValue) {
if (newValue > 2004) {
this._year = newValue
this.edition += newValue - 2004
}
}
}
book.year = 2005
alert(book.edition) //2
_前缀一般是私有字段算是命名规范吧 var book = {};
Object.defineProperties(book, {
_year: {
value: 2004,
writable: true // 默认false
},
edition: {
value: 1,
writable: true // 默认false
},
year: {
get: function(){
return this._year;
},
set: function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
}
});
book.year = 2005;
console.dir(book);
alert(book.edition); //2
可能是教材比较老了吧。