我尝试在Javascript中行使继承性。从汽车继承的eCar从汽车继承的汽车。但似乎我无法将方法“ 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>");
您很亲密,只需要几件事就可以有所不同。
// Vehicle
function Vehicle(herst){
this.manuf = herst;
}
Vehicle.prototype.getInfo = function () {
return 'Manufacture: '+ this.manuf+'<br>'; // you really want to return HTML?
};
Vehicle.prototype.construtor = Vehicle;
// Car
function Car(){
Vehicle.apply(this, arguments); // extends Vehicle
}
Car.prototype = Object.create(Vehicle.prototype); // inherits Vehicle's prototype
Car.prototype.construtor = Car;
// eCar
function eCar(){ // constructors usually start with a capital
Car.apply(this, arguments); // extends Car
}
eCar.prototype = Object.create(Car.prototype);
eCar.prototype.construtor = eCar;
// use it
var Train = new Vehicle('Siemens'), // variables usually start lower case
Golf = new Car('VW'),
Tesla = new eCar('Tesla');
我选择Object.create
设置继承,有些人喜欢使用的格式,Bar.prototype = new Foo()
但是我觉得这会Foo
在错误的时间调用构造函数。
看起来像什么?
var foo = new eCar('Foo');
foo instanceof eCar; // foo has eCar's prototype
// eCar was used to construct foo
foo instanceof Car; // foo inherited Car's prototype via eCar's prototype
// at the beginning of eCar, Car was applied to foo
foo instanceof Vehicle; // foo inherited Vehicle's prototype via Car's prototype
// at the beginning of Car, Vehicle was applied to foo
/*
So `foo` has own properties as assigned by Vehicle, then Car, then eCar,
and it has the prototype from eCar which shadows the prototype from Car
which again shadows the prototype from Vehicle
*/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句