Object.defineProperty

Object.defineProperty(obj, prop, descriptor)

descriptor分成data descriptor和access descriptor,兩者不能混用。
If a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both value or writable and get or set keys, an exception is thrown.

這兩者差別在於 data descriptor描述值與是否可以更改值,access descriptor將值則是用getter/setter來處理
data descriptor:
value: default undefined
writable: true 可以變更值
access descriptor:
get: function(){ return v;} //沒設定的話value會是undefined
set: function(v){} //當obj.prop = v時會呼叫
其他可以設定的是
configurable: true 可刪掉
enumerable: true 可在for(var prop in obj) 或是Object.keys(obj)列出

以上的設定如果不是使用Object.defineProperty 預設 writable: true, enumerable: true, configurable: true
使用Object.defineProperty的預設是 { value: undefined, writable: false, enumerable: false, configurable: false }
By default, values added using Object.defineProperty() are immutable (writable預設false)
所以不論是data descriptor或是access descriptor沒有設定value or getter,取得值的話都是undefined

這個主要用在做更細的權限控制,特別是寫library時,以及將method隱藏在enumeration
另外透過get set hook,可以將物件對象和外部資源進行連結。

參考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

This entry was posted in nodejs. Bookmark the permalink.

Leave a Reply