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

时间:2018-09-06 02:07:32

标签: javascript oop inheritance prototype

因此,我不熟悉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();

当您运行代码时,即使我说汽车具有瓦斯能源类型,它也会显示“此车正在未定义的状态下运行”?

3 个答案:

答案 0 :(得分:2)

.call时,第一个参数应该是您要调用的函数引用的this。所以,

Vehicle.call(energyType, energy);

使用{em> one 参数调用Vehicle,其中this的值最初是变量energyType的值(强制为对象,因为{ {1}}必须是一个对象,而不是原始对象。如果您在thisconsole.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();