在继承中设置proto.constructor

时间:2014-12-09 22:23:25

标签: javascript oop

在javascript中实现继承的方法有哪些?我对OOPS感到困惑,因为我看到了做同样事情的不同方式。

以下是simple parent/child关系。

function Plant () {
​   this.country = "Mexico";
​   this.isOrganic = true;
}
​
​Plant.prototype.showNameAndColor =  function () {
    console.log("I am a " + this.name + " and my color is " + this.color);
}
​
​Plant.prototype.amIOrganic = function () {
    ​if (this.isOrganic)
    console.log("I am organic, Baby!");
}
​
​function Fruit (fruitName, fruitColor) {
​    this.name = fruitName;
​    this.color = fruitColor;
}
​
​Fruit.prototype = new Plant ();
​var aBanana = new Fruit ("Banana", "Yellow");
​console.log(aBanana.name); // Banana​
​console.log(aBanana.showNameAndColor()); // I am a Banana and my color is yellow.

第一个问题:

我在一些代码中看到过设置孩子的构造函数,这让我很困惑?为什么人们也设置了Fruit.prototype.constructor = Plant;

以下代码是否不足以实现继承     Fruit.prototype = new Plant(); // Fruit has all methods/properties of Plant Object

第二个问题:

将值传递给Super构造函数。

Fruit.prototype = new Plant ("Aus", true);

function Fruit (fruitName, fruitColor) {
    Plant.call(this,"Aus", true);
​    this.name = fruitName;
​    this.color = fruitColor;
}

为什么在将参数传递给父constructor时,前者总是优先于后者?

0 个答案:

没有答案