兩個問題與該代碼:
使用new Plant()
創建Fruit.prototype
是可悲共用反模式;而是使用Object.create
並從Fruit
內撥打電話Plant
。它在你的特定代碼中並不重要,但是如果你想從Fruit
中獲得某些東西,或者想要使country
成爲Plant
的一個參數,那麼這很重要。
如果您希望它指向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;
};
}
沒有,constructor屬性「[返回到創建該實例的原型對象函數的引用(https://開頭開發商.mozilla.org/EN-US /文檔/網絡/的JavaScript /參考/ Global_Objects /對象/構造函數)」。 – 1983