2015-06-15 91 views
0

我有以下一段代碼用於學習JS。Javascript原型繼承和對象構造函數

function CircleArea(x) 
{ 
    this.x = x; 
} 

CircleArea.prototype = 
{ 
    area: function() { 
     return 22/7 * this.x * this.x; 
    } 
}; 

var CalArea = new CircleArea(7); 
if(CalArea.constructor === CircleArea.prototype.constructor) 
{ 
    alert(CalArea.area()); 
} 

我通過分配對象文本CircleArea.prototype解耦繼承鏈,然後使用CircleArea構造定義CalArea對象。現在,CalArea.constructor和CircleArea.prototype.constructor基本上都是Object構造函數而不是CircleArea構造函數,但是當我在alert函數內調用CalArea.area()時,this.x獲得7作爲其值,而值7作爲參數傳遞給CircleArea構造函數而不是CalArea.constructor和CircleArea.prototype構造函數現在引用的Object構造函數。

+2

相關:[爲什麼要設置原型構造?(http://stackoverflow.com/questions/8453887/why-is-it-necessary-to- set-the-prototype-constructor) –

+3

你的問題是什麼? –

+0

問題是何時CalArea構造函數和CircleArea原型構造函數引用Object構造函數如何調用CalArea對象上的area()方法獲取this.x = 7.雖然將值7傳遞給CircleArea構造函數而不是Object構造函數? – user2913184

回答

0

我不確定「解耦繼承鏈」是什麼意思,但對我來說,你正在經歷的是預期的行爲。

您在CircleArea的實例上致電area()

area()使用this.x

this在這種情況下,您的CircleArea的實例有x=7

所以你的計算是22/7 * 7 * 7

如果你期望不同的東西,你能解釋一下你期待什麼,以及爲什麼你期待嗎?


我猜測,你的困惑,從被設置爲對象實例,一個函數被調用,所以叫CalArea.area()this莖意味着this設置爲CalArea所以this.x相同CalArea.x

+0

嗯,我還挺知道你的觀點是什麼,但我的困惑是,當CalArea.constructor爲對象構造不CircleArea構造函數是怎麼來傳遞給CircleArea構造一種說法是提供價值爲對象CalArea其構造函數對象不CircleArea – user2913184

+1

@ user2913184:我建議你設置'CircleArea.prototype.constructor =函數foo(){}',** **後您創建'CalArea',然後有看'CalArea.constructor'。根據你的邏輯,'CalArea'應該由'Foo'構造,但我們都知道情況並非如此。 'CalArea.constructor'只是指'CircleArea.prototype.constructor',並且該值在構造對象本身時不起作用。 –

+0

所以你的意思,雖然CalArea構造將是富構造函數,但它實際上起着CalArea itslef建設任何部分。我是對的先生? – user2913184

0

當您將對象分配給原型(CircleArea.prototype = {area:fun ..})時,您只需調度默認的CircleArea.prototype,然後調度CircleArea.prototype.constructor。但CircleArea仍然是構造函數,當您使用operator new時,它會返回CircleArea的對象實例({x:argument,proto:{area:fun,proto:...}})。 您只能使用新的CalArea.constructor(),但可以使用新的CircleArea()。新CalArea.constructor()返回對象實例