原型對象

原型對象

這裏不介紹原型鏈。javascript

javascript 中有若干長得跟 "prototype" / "proto" 很想的屬性/函數,這裏簡單總結一下他們都是啥,哪一個是原型對象,哪一個不是。java

[[Prototype]]

這個對象的一個內置槽,對程序員是不可見(不能直接操做)的。[[Prototype]] 記錄了 javascipt 對象的原型對象。node

ECMA262 關於它有以下介紹):程序員

All ordinary objects have an internal slot called [[Prototype]]. The value of this internal slot is either null or an object and is used for implementing inheritance. Data properties of the [[Prototype]] object are inherited (and visible as properties of the child object) for the purposes of get access, but not for set access. Accessor properties are inherited for both get access and set access.

[[GetPrototypeOf]]

這也是對象的一個內置槽,程序員沒法直接操做。它是一個方法,用於獲取對象的 [[Prototype]] 槽。瀏覽器

在 ECMA262 中,除了 Proxy 類型的對象,其它對象的 [[GetPrototypeOf]] 直接返回 [[Prototype]] 的值。less

Object.getPrototypeOf(O)

Object 對象的 getPrototypeOf 方法。這個是程序員能夠調用的。當 O 爲對象時,返回 O.[[GetPrototypeOf]]()函數

這是程序員能夠使用的獲取 O 的原型對象的方法。this

Object.prototype.__proto__

obj.__proto__ 也是 javascript 裏經常使用的一種獲取原型對象的方式。它實際是一個 getter / setterprototype

用做 getter 時,obj.__proto__ 返回 obj.[[GetPrototypeOf]]() ,也就是能夠取得 obj 的原型對象。與 Object.getPrototypeOf(obj) 結果是一致的。code

根據 ECMA262 ,這一屬性僅在瀏覽器中提供。不夠貌似 node 也提供了這一屬性。

因爲它定義在 Object.prototype 上,因此,僅當 Object.prototypeobj 的原型鏈上時,才能夠使用這一屬性。當 Object.prototype 不在原型鏈上時(例如經過 Object.create(null) 生成的對象),沒法使用這一屬性。Object.getPrototypeOf(O) 則無此限制。

prototype

這是一個看起來很像原型對象的屬性,可是,它不是所在對象的原型對象。即,obj.prototype 不是 obj 的原型對象。

構造函數都有此屬性。ECMA262 中關於它的介紹以下:

Function instances that can be used as a constructor have a prototype property. Whenever such a Function instance is created another ordinary object is also created and is the initial value of the function's prototype property. Unless otherwise specified, the value of the prototype property is used to initialize the [[Prototype]] internal slot of the object created when that function is invoked as a constructor.

This property has the attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }.

一般狀況下,當使用構造函數(F)構造一個新對象(obj)時,構造函數的 prototype 屬性(F.prototype),將成爲新對象的原型對象(obj.[[Prototype]])。

F.prototype 不是 F 的原型對象。F.prototype 一般狀況下是 new F(...) 的原型對象。

instanceof

obj instanceof F 檢查 obj 是不是 F 的實例。它並不是檢查 F 是否在 obj 的原型鏈上。這一檢查要求 F 是一個構造函數,並檢查 F.prototype 是否在 obj 的原型鏈上。

InstanceOfOperator(V, target)

The abstract operation InstanceofOperator( V, target) implements the generic algorithm for determining if ECMAScript value V is an instance of object target either by consulting target's @@hasinstance method or, if absent, determining whether the value of target's prototype property is present in V's prototype chain.

一般所說的 objF 類型的對象,指的也是 F.prototypeobj 的原型鏈上。

相關文章
相關標籤/搜索