定義(Definition).定義屬性需要使用相應的函數,比如:
Object.defineProperty(obj, "prop", propDesc)
如果obj沒有prop這個自身屬性,則該函數的作用是給obj添加一個自身屬性prop並賦值,
參數propDesc指定了該屬性擁有的特性(可寫性,可枚舉性等).
如果obj已經有了prop這個自身屬性,則該函數的作用是修改這個已有屬性的特性,當然也包括它的屬性值.
1、defineProperty
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 = 2005;
alert(book.edition); //2
2、__defineSetter__ 和 __defineGetter__
var book = {
_year: 2004,
edition: 1
};
//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學習小結,之後每天還會繼續更新,希望大家繼續關注。