要在對(duì)象上定義多個(gè)屬性,使用Object.defineProperties()而不是Object.defineProperty()。
此方法接受兩個(gè)參數(shù):要處理的對(duì)象和一個(gè)包含所有屬性信息的對(duì)象。
以下代碼定義了兩個(gè)屬性:
var book1 = {};
/* w w w . j av a 2 s. c o m*/
Object.defineProperties(book1, {
// data property to store data
_name : {
value : "Javascript",
enumerable : true,
configurable : true,
writable : true
},
// accessor property
name : {
get : function() {
console.log("Reading name");
return this._name;
},
set : function(value) {
console.log("Setting name to %s", value);
this._name = value;
},
enumerable : true,
configurable : true
}
});
更多建議: