我們知道JS是面對對象的編程語言,但其實(shí)很多人對JS中的對象沒有足夠的理解。這次我們從ES規(guī)范入手,深入的理解object。
我們來看看ES規(guī)范是如何定義object的:
- An Object is logically a collection of properties.
- Each property is either a data property, or an accessor property
- A data property associates a key value with an ECMAScript language value and a set of Boolean attributes.
- An accessor property associates a key value with one or two accessor functions, and a set of Boolean attributes. The accessor functions are used to store or retrieve an ECMAScript language value that is associated with the property.
可以看到,一個(gè)object就是由一個(gè)個(gè)屬性(property)以及屬性描述符(attributes)組成的。而屬性又分為兩種,數(shù)據(jù)屬性(data property)和訪問屬性( accessor property)。
比如說上述的obj1,它就有兩個(gè)數(shù)據(jù)屬性a b,他們的值分別為1 2。那它的屬性描述符是什么呢?

截圖自ECMAScript
我們可以再JS代碼中這樣查看:
var obj1 = {
a: 1,
b: 2
}
console.log(Object.getOwnPropertyDescriptor(obj1, 'a'))
{ value: 1, writable: true, enumerable: true, configurable: true }
這就是對象的全部面貌嗎?好有很多