我正在学习javascript继承。我在这里找到了一个很好的解释:JavaScript Inheritance
function A() {
B.call(this);
}
function B() {
C.call(this);
this.bbb = function() {
console.log("i was inherited from b!");
}
}
我正在尝试实现基于上述和其他解决方案的继承(网上有很多这样的解决方案,它们似乎都有不同的建议)。无论如何,我正在尝试让SportsCar
继承Car
并使用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();
,并得到关于我目前做错了什么的解释。
发布于 2016-08-14 07:43:46
添加使用add this
注释的行。
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;
};
// add this
SportsCar.prototype = Object.create( Car.prototype );
var fordGt = new SportsCar('V8', 'ford', 205 , 'red');
fordGt.describeSelf();
这是因为您确实希望正确设置原型链,以便新创建的对象在链中具有其父原型。
另一方面,如果您将该方法附加到对象本身
var Car = function(make, topSpeed, color){
this.make = make;
this.topSpeed = topSpeed;
this.color = color;
this.describeSelf = function() ...
}
链可以被忽略(因为您已经从另一个构造函数调用了构造函数,但是您最终会将同一函数的多个实例附加到新创建的实例上。
发布于 2020-03-16 10:59:04
你可以继续这样做
this.make = make;
this.topSpeed = topSpeed;
this.color = color;
this.engineSize = engineSize;
,而不是使用call方法。但也许有时会有很多争论,你不会重复自己的话。call方法所做的是:
它运行Car构造函数中的代码,就好像代码是在sportCar构造函数中编写的一样。这是通过.call()方法中的'this‘参数完成的。
不过,在超继承的方式中,同样的事情是由ES6 ()方法完成的,这是必须的。
https://stackoverflow.com/questions/38940005
复制相似问题