內部屬性 「[Class」]

內部屬性 [[Class]]

所有 typeof 返回值為 "object" 的對象(如數組)都包含一個內部屬性 [[Class]](我們可 以把它看作一個內部的分類,而非傳統的面向對象意義上的類)。這個屬性無法直接訪問, 一般通過 Object.prototype.toString(..) 來查看。例如:

Object.prototype.toString.call( [1,2,3] ); // "[object Array]"

Object.prototype.toString.call( /regex-literal/i ); // "[object RegExp]"

上例中,數組的內部 [[Class]] 屬性值是 "Array",正則表達式的值是 "RegExp"。多數情況下,對象的內部 [[Class]] 屬性和創建該對象的內建原生構造函數相對應(如下),但並非 總是如此。

那麼基本類型值呢?下面先來看看 null 和 undefined:

Object.prototype.toString.call( null ); // "[object Null]"

Object.prototype.toString.call( undefined ); // "[object Undefined]"

雖然 Null() 和 Undefined() 這樣的原生構造函數並不存在,但是內部 [[Class]] 屬性值仍 然是 "Null" 和 "Undefined"。

其他基本類型值(如字符串、數字和布爾)的情況有所不同,通常稱為“包裝”

Object.prototype.toString.call( "abc" ); // "[object String]"

Object.prototype.toString.call( 42 ); // "[object Number]"

Object.prototype.toString.call( true ); // "[object Boolean]"

上例中基本類型值被各自的封裝對象自動包裝,所以它們的內部 [[Class]] 屬性值分別為 "String"、"Number" 和 "Boolean


分享到:


相關文章: