所以我在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();
当你运行代码时,它说“这辆车正在运行未定义”,尽管我说汽车有汽油能量类型......?
当你.call
时,第一个参数应该是你希望被调用函数引用的this
。所以,
Vehicle.call(energyType, energy);
导致用一个参数调用Vehicle
,其中this
值最初是energyType
变量(强制转换为一个对象,因为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);
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();
它缺少一个this
。
Vehicle.call(this, energyType, energy);
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();