【发布时间】:2014-04-25 11:21:22
【问题描述】:
我尝试在 Javascript 中行使继承权。 eCar 继承自 car 继承自 Vehicle 的汽车。但似乎我不能将方法“getInfo()”与 Car- 或 eCar-Object 一起使用。 如果我在浏览器中执行此操作,结果是:
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>");
【问题讨论】:
-
我建议看看Introduction to Object-Oriented JavaScript。它提供了有关如何设置继承的示例。
-
我认为是
Car.prototype = new Vehicle();和eCar.prototype = new Car();等,不是吗? -
@Andy 最好不要,您正在创建一个 Vehicle 实例来设置 Car 的原型。 Vehicle 具有实例特定成员,这些成员现在位于 Car 的共享原型上,并且可能会产生意想不到的结果。您可以通过在 Car 构造函数中使用
Vehicle.call(this,args)来调解这一点,但是当在定义对象时创建 Vehicle 的实例不方便时,您仍然会遇到麻烦。更好地为旧浏览器使用 Object.create 和 polyfil -
@HMR,这很有趣。感谢您的反馈。
标签: javascript object inheritance methods