Javascript es6 class inheritance



有人可以向我解释为什么从子级调用父函数是重置父类变量。

class Garages {
constructor() {
this.garages = {};
}
addGarage(id) {
this.garages[id] = {id};
return this.garages[id];
}
getGarage(id) {
alert(this.garages[id]); //why undefined?
}
}
class Cars extends Garages {
constructor() {
super();
this.cars = [];
}
getGarageByID(id) {
this.getGarage(id)
}
}
const cars = new Cars();
const garages = new Garages();
console.log(garages.addGarage("one"))
cars.getGarageByID("one")

小提琴

因为汽车的实例与车库不同,所以你应该这样写:

alert(cars.addGarage("one")) //alerts object
alert(cars.getGarageByID("one"))

问题 #1是你正在添加到一个实例并要求另一个实例为你获取值。

问题#2是您没有从getGarageByID返回任何内容,因此您会得到undefined

将您的代码更改为以下内容:

class Garages {
constructor() {
this.garages = {};
}
addGarage(id) {
this.garages[id] = {id};
return this.garages[id];
}
getGarage(id) {
return this.garages[id];
}
}
class Cars extends Garages {
constructor() {
super();
this.cars = [];
}
getGarageByID(id) {
return this.getGarage(id)
}
}
const cars = new Cars();
console.log(cars.addGarage("one"))
console.log(cars.getGarageByID("one"))

你应该让两者都打印出来。

最新更新