2017-01-16 40 views
1

我試圖回去並更好地理解原型繼承。我知道一個實例的__proto__屬性指向構造函數的prototype對象,但構造函數的__proto__屬性指向什麼?構造函數的__proto__屬性指向什麼?

我曾假設由於構造函數本身就是函數的一個實例,它將指向函數構造函數的prototype對象,但下面顯示它是一個空函數。

var Example = function(){ 
    this.attribute = 'example'; 
} 

var exampleInstance = new Example(); 

exampleInstance.__proto__ === Example.prototype // true 
Example.__proto__ // function() {} 

[編輯] Ovidiu Dolha現在證實了我的理解,所以也許這對別人會有幫助。

enter image description here

回答

3

Example.__proto__將是一樣Function.prototype,就像exampleInstance.__proto__相同Example.prototype

這是因爲Example是函數的一個實例。

一切都將最終得到Object.prototype這是原型繼承的根源。

請注意,如果可能的話,您應該避免使用__proto__,因爲它被視爲已棄用。相反使用Object.getPrototypeOf()

+0

謝謝。所以我的假設是正確的,並且'Example .__ proto__'返回一個空函數是控制檯的一個怪癖。 – Undistraction

+0

嗯,我實際上認爲'Function.prototype'是空的,因爲它在被調用時什麼也不做 - 如果我用'Object.getOwnPropertyNames(Function.prototype)'看它,那麼我可以看到它有一些屬性/方法。原型是這樣使用的(即它是一個數據和方法的持有者,例如構造函數定義 - 在這種情況下爲函數) –

+0

但是,它肯定應該是一個對象,而不是函數。你不要調用它。 – Undistraction

0

它肚裏,直到它找到「對象」爲根末端的原型鏈。

ECMAScript的5.1規範規定這樣的:

函數原型對象的屬性15.3.4:

The value of the [[Prototype]] internal property of the Function prototype object is the standard built-in Object prototype object 

和對象原型對象的屬性15.2.4

The value of the [[Prototype]] internal property of the Object prototype object is null 

在你的控制檯中試試這個。

console.log(exampleInstance); 

Example 
attribute 
: 
"example" 
__proto__ 
: 
Object 
constructor 
: 
() 
__proto__ 
: 
Object 
__defineGetter__ 
: 
__defineGetter__() 
__defineSetter__ 
: 
__defineSetter__() 
__lookupGetter__ 
: 
__lookupGetter__() 
__lookupSetter__ 
: 
__lookupSetter__() 
constructor 
: 
Object() 
hasOwnProperty 
: 
hasOwnProperty() 
isPrototypeOf 
: 
isPrototypeOf() 
propertyIsEnumerable 
: 
propertyIsEnumerable() 
toLocaleString 
: 
toLocaleString() 
toString 
: 
toString() 
valueOf 
: 
valueOf() 
get __proto__ 
: 
__proto__() 
set __proto__ 
: 
__proto__() 
相關問題