我正在学习JavaScript继承。我发现了一个很好的解释在这里: JavaScript Inheritance不理解Javascript继承
function A() {
B.call(this);
}
function B() {
C.call(this);
this.bbb = function() {
console.log("i was inherited from b!");
}
}
我想基于以上和其他的解决方案来实现继承(有一群人在网上,他们都似乎表明不同的东西)。无论如何,我试图让SportsCar
继承Car
并使用汽车的describeSelf
方法。我不确定我做错了什么。 PLUNK for convenience
var Car = function(make, topSpeed, color){
this.make = make;
this.topSpeed = topSpeed;
this.color = color;
}
Car.prototype.describeSelf = function(){
document.write('Hi, I am a: ' + this.make + ', my top speed is ' + this.topSpeed + ' and I am ' + this.color);
}
var corolla = new Car('toyota', 120, 'blue');
corolla.describeSelf();
//Code works fine up to here
var SportsCar = function(engineSize, make, topSpeed, color) {
Car.call(this, make, topSpeed, color);
this.engineSize = engineSize;
};
var fordGt = new SportsCar('V8', 'ford', 205 , 'red');
fordGt.describeSelf();
我真不明白什么call
一样。
编辑:看起来我不清楚我在问什么。问题的实质是让这条线路工作:fordGt.describeSelf();
并得到我目前做错了什么的解释。
@JaromandaX我欣赏这个链接,但是这并没有帮助我理解如何向子对象的构造函数添加新属性MDN上的示例不会传递新的道具 – VSO
我的问题是如何使继承正常工作,例如如何使这条线工作:fordGt.describeSe如果();我会更新这个问题。 – VSO
你绝对没有在SportCar的原型链中设置Car'SportCar.prototype = Object.create(Car);'。 –