2013-04-25 38 views
1
function Test() 
{ 
    this.name = 'test name'; 
} 


console.log(Test.prototype.constructor.prototype.constructor); 

我不明白爲什麼這是一個constructor無限鏈 - prototypeJavaScript的原型構造混亂

我的意思是這個鏈的目的是什麼,爲什麼沒有結束,原型有一個構造函數,構造函數有一個原型,它是一個循環鏈,每次構造函數都是一樣的,無法想象...

回答

3

不錯,每函數對象,在默認情況下有一個.prototype屬性,該屬性引用原型對象這個函數(如果用作構造成爲唯一重要的)。

默認情況下,每個prototype object都有一個對constructor函數的引用,當然這個函數指向構造函數(在您的示例中爲Test())。

所以,在這裏我們去

Test.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor 
+0

hmmm也是prototype.constructor.constructor.constructor。 - 作品,令人難以置信,仍試圖理解......謝謝 – Hello 2013-04-25 17:42:08

+0

@你好,如果你仔細觀察'.prototype.constructor.constructor',你會注意到這引用了'Function()'的基本構造函數。記住,一個函數也是這個語言中的一個* object *。 – jAndy 2013-04-25 17:43:30

0

這是一個預期的行爲。 原型的constructor屬性指的是擁有原型的對象(所以它引用自己)。