调用原型成员时,JavaScript返回'undefined'

问题描述 投票:1回答:3

所以我在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();

当你运行代码时,它说“这辆车正在运行未定义”,尽管我说汽车有汽油能量类型......?

javascript oop inheritance prototype
3个回答
2
投票

当你.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();

1
投票

它缺少一个this

Vehicle.call(this, energyType, energy);

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();
© www.soinside.com 2019 - 2024. All rights reserved.