設(shè)置對(duì)象的屬性,可以有兩種方法:
1、使用構(gòu)造函數(shù)和字面量的形式
let aa = {}
aa.name = 'miaomiao'
aa.say = function() {}
2、使用Object.defineProperty()給對(duì)象添加屬性
語(yǔ)法
Object.defineProperty(obj, prop, descriptor)
返回值
返回值為傳入的對(duì)象obj
參數(shù)釋意
obj: 傳入的需要新增或修改屬性的對(duì)象;
prop: 新增或者修改的屬性;
descriptor: 對(duì)屬性prop添加特性描述;
descriptor
目前給對(duì)應(yīng)的屬相添加特性有兩種形式:
1、數(shù)據(jù)描述
value: 屬性值, // 任意類(lèi)型的值,默認(rèn)undefined
writable: true, | false // 是否可寫(xiě),默認(rèn)為false
enumerable: true, | false // 是否可被for in 或 Object.keys()枚舉到
configurable: true | false // 是否可以刪除目標(biāo)屬性,或 是否可以重寫(xiě)屬性的其他特性,默認(rèn)false
2、存取器描述
設(shè)置或讀取目標(biāo)屬性的值
getter 是一種獲取屬性值的方法
setter 是一種修改屬性值得方法
注意:使用存取器描述時(shí),不能使用value和writable特性
實(shí)例如下:
let aa = {}
let initValue = 'hello'
Object.defineProperty(aa, 'newKey', {
get: function () {
return initValue
},
set: function (value) {
initValue = value
},
enumerable: true,
configurable: true
})
console.log(aa.newKey) // 'hello'
aa.newKey = 'hello word'
console.log(aa.newKey) // 'hello word'
注意:使用Object.defineProperty給屬性添加特性時(shí),沒(méi)有寫(xiě)出的特性都是默認(rèn)為默認(rèn)值,writable/enumerable/configurable默認(rèn)都為false。