因此,我不熟悉JavaScript中的OOP,并且无法理解为什么在以下代码中得到“未定义”的原因,请帮忙:
function Vehicle(energyType, energy) {
this.energyType = energyType;
this.energy = energy;
}
function Car(energyType, energy) {
Vehicle.call(energyType, energy);
this.doors = 4;
}
Car.prototype = Object.create(Vehicle.prototype);
Vehicle.prototype.run = function() {
console.log(`This vehicle is running on ${this.energyType}.`);
}
const c = new Car('gas', 80);
c.run();
当您运行代码时,即使我说汽车具有瓦斯能源类型,它也会显示“此车正在未定义的状态下运行”?
答案 0 :(得分:2)
当.call
时,第一个参数应该是您要调用的函数引用的this
。所以,
Vehicle.call(energyType, energy);
使用{em> one 参数调用Vehicle
,其中this
的值最初是变量energyType
的值(强制为对象,因为{ {1}}必须是一个对象,而不是原始对象。如果您在this
内console.log
,可以看到以下内容:
Vehicle
更改为:
function Vehicle(energyType, energy) {
console.log('this', this);
console.log('energyType', energyType);
console.log('energy', energy);
this.energyType = energyType;
this.energy = energy;
}
function Car(energyType, energy) {
Vehicle.call(energyType, energy);
this.doors = 4;
}
Car.prototype = Object.create(Vehicle.prototype);
Vehicle.prototype.run = function() {
console.log(`This vehicle is running on ${this.energyType}.`);
}
const c = new Car('gas', 80);
c.run();
Vehicle.call(this, energyType, energy);
答案 1 :(得分:1)
它缺少this
。
Vehicle.call(this, energyType, energy);
答案 2 :(得分:1)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
function.call(thisArg,arg1,arg2,...)
通过this
中的Vehicle.call(this,energyType, energy);
function Vehicle(energyType, energy) {
this.energyType = energyType;
this.energy = energy;
}
function Car(energyType, energy) {
Vehicle.call(this,energyType, energy);
this.doors = 4;
}
Car.prototype = Object.create(Vehicle.prototype);
Vehicle.prototype.run = function() {
console.log(`This vehicle is running on ${this.energyType}.`);
}
const c = new Car('gas', 80);
c.run();