在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
时,前者总是优先于后者?