Object.defineProperty()

設(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。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容