定义(Definition).
定义属性需要使用相应的函数,比如:
如果obj没有prop这个自身属性,则该函数的作用是给obj添加一个自身属性prop并赋值,
参数propDesc指定了该属性拥有的特性(可写性,可枚举性等).
如果obj已经有了prop这个自身属性,则该函数的作用是修改这个已有属性的特性,当然也包括它的属性值.
1、defineProperty
Object.defineProperty(book,"year",{
get: function(){
return this._year;
},set: function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
});
book.year = 2005;
alert(book.edition); //2
2、__defineSetter__ 和 __defineGetter__
//legacy accessor support
book.defineGetter("year",function(){
return this._year;
});
book.defineSetter("year",function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
});
book.year = 2005;
alert(book.edition); //2
以上就是今天的javascript学习小结,之后每天还会继续更新,希望大家继续关注。
原文链接:https://www.f2er.com/js/51628.html
get: function(){
return this._year;
},set: function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
});
book.year = 2005;
alert(book.edition); //2
book.defineGetter("year",function(){
return this._year;
});
book.defineSetter("year",function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
});
book.year = 2005;
alert(book.edition); //2