要在對象上定義多個屬性,使用Object.defineProperties()而不是Object.defineProperty()。
此方法接受兩個參數:要處理的對象和一個包含所有屬性信息的對象。
以下代碼定義了兩個屬性:
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
}
});
更多建議: