2015-07-28 25 views
0
function Plant() { 
    this.country = "Mexico" 
    this.isOrganic = true; 
} 

function Fruit(fName, fColor) { 
    this.name = fName; 
    this.color = fColor; 
} 

Fruit.prototype = new Plant(); 

var abanana = new Fruit("Banana", "Yellow") 
console.log(abanana.constructor) 

所以在我的代碼中,我試圖玩弄原型繼承。每次創建Fruit的新實例(var aFruit = new Fruit())時,新實例的原型將被分配爲Fruit構造函數的原型,即Fruit.prototype。Javascript構造函數方法返回與預期不同的東西

那麼爲什麼abanana.constructor 不

[function: Fruit] 

[function: Plant]? 

我認爲這是什麼構造方法做:

而且,繼承所有對象另一個對象也繼承了一個構造函數屬性。而這個構造函數屬性只是一個屬性(像任何變量),它保存或指向對象的構造函數。

+0

沒有,constructor屬性「[返回到創建該實例的原型對象函數的引用(https://開頭開發商.mozilla.org/EN-US /文檔/網絡/的JavaScript /參考/ Global_Objects /對象/構造函數)」。 – 1983

回答

3

兩個問題與該代碼:

  1. 使用new Plant()創建Fruit.prototype是可悲共用反模式;而是使用Object.create並從Fruit內撥打電話Plant。它在你的特定代碼中並不重要,但是如果你想從Fruit中獲得某些東西,或者想要使country成爲Plant的一個參數,那麼這很重要。

  2. 如果您希望它指向Fruit,您需要在Fruit.prototype上設置constructor

所以:

function Plant() { 
    this.country = "Mexico" 
    this.isOrganic = true; 
} 

function Fruit(fName, fColor) { 
    Plant.call(this);        // ** 
    this.name = fName; 
    this.color = fColor; 
} 

Fruit.prototype = Object.create(Plant.prototype); // ** 
Fruit.prototype.constructor = Fruit;    // ** 

當然,作爲ES2015的,我們有class語法,你可以利用今天與transpiler(或者,如果你只需要支持Chrome和Firefox的最新版本):

class Plant { 
    constructor() { 
     this.country = "Mexico"; 
     this.isOrganic = true; 
} 

class Fruit extends Plant { 
    constructor(fName, fColor) { 
     super(); 
     this.name = fName; 
     this.color = fColor; 
    } 
} 

我認爲這是什麼構造方法做:

此外,從另一個對象繼承的所有對象也都繼承了一個構造函數屬性。而這個構造函數屬性只是一個屬性(像任何變量),它保存或指向對象的構造函數。

constructor不是方法,它是指在prototype對象是有關功能的屬性。 JavaScript本身並沒有使用constructor來表示任何東西,但是確定對於所有具有prototype屬性的函數,當函數首次創建時,屬性指向的對象將具有指向該函數的constructor屬性。但是由於您替換爲的值爲prototype並且引用了另一個對象,因此必須更新constructor屬性,以便它再次指向正確的功能(如果您希望徹底,那麼最好是  —甚至是雖然JavaScript不使用它,但這並不意味着庫不使用它)。


在真正舊​​的瀏覽器上,您可能需要墊片Object.create。它不能完全墊高,但它可以爲上述足夠:

if (!Object.create) { 
    Object.create = function(p, props) { 
     if (typeof props !== "undefined") { 
      throw new Error("The second argument of Object.create cannot be shimmed."); 
     } 
     function ctor() { } 
     ctor.prototype = p; 
     return new ctor; 
    }; 
} 
+0

你的意思是從水果中得到什麼東西? – Jwan622

+0

@ Jwan622:就像你從'Plant'派生'Fruit'一樣。 –

+0

我得到了什麼嗎?我只是將Fruit的原型對象設置爲植物對象? – Jwan622

相關問題