私はJavascriptで継承を行使しようとしています。車から継承されたeCar車両から継承された車。しかし、Car-またはeCar-Objectでメソッド "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>");
あなたは近くにいました、ただいくつかのことを変える必要がありました。
// 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]
コメントを追加