0
我尝试在Javascript中行使继承性。 eCar从继承自Vehicle的汽车继承。但似乎我不能使用带Car或eCar对象的方法“getInfo()”。 如果我在浏览器中执行这样的结果是:。我是否继承了对象的方法?我怎样才能达到结果?
Manufacture: Siemens
undefined
undefined
请告诉我我在寻找的是:
Manufacture: Siemens
Manufacture: VW
Manufacture: Tesla
。
function Vehicle(herst){
this.manuf = herst;
}
Vehicle.prototype.getInfo = function(){
return 'Manufacture: '+ this.manuf+'<br>';
}
Car.prototype = Vehicle;
Car.prototype.construtor = Vehicle;
Car.prototype.getInfo = Vehicle;
function Car(){ }
eCar.prototype = Car;
eCar.prototype.construtor = Car;
eCar.prototype.getInfo = Car;
function eCar(){ }
Train = new Vehicle('Siemens');
document.write(Train.getInfo()+"<br>");
Golf = new Car('VW');
document.write(Golf.getInfo()+"<br>");
Tesla = new eCar('Tesla');
document.write(Tesla.getInfo()+"<br>");
我建议看看[简介面向对象的JavaScript(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript)。它提供了一个关于如何设置继承的例子。 –
我认为它是'Car.prototype = new Vehicle();'和'eCar.prototype = new Car();'等等不是吗? – Andy
@最好不要,你正在创建一个Vehicle实例来设置Car的原型。车辆具有特定于实例的成员,它们现在处于Car的共享原型上,并且可能会有意想不到的结果。您可以通过在Car构造函数中使用'Vehicle.call(this,args)'来调解,但在定义对象时创建Vehicle的实例时仍然会遇到麻烦。更好地使用Object.create和polyfil它为旧版浏览器 – HMR