以下代码的输出是undefined has undefined wheels而不是Bike has 2 wheels
Instantiated object是否无法调用未附加到任何对象的prototype的函数?



var vehicle = function(name, wheels){
	name = "car",
	wheels = 4,
	fuel = "petrol"
}

function drive(name, wheels) {
	console.log(this.name + " has " + this.wheels + " wheels" );
}

var vehicle1 = new vehicle('Bike' , 2);
drive.call(vehicle1); //undefined is driven with undefined wheels 

最佳答案

不幸的是,关于代码的几乎所有内容都不正确。

首先,“车辆”功能必须在this上设置属性,并且应使用传入的参数而不是常量:

var vehicle = function(name, wheels) {
    this.name = name,
    this.wheels = wheels,
    this.fuel = "petrol"
}


然后,您的函数“驱动器”应该根本不带任何参数:

function drive() {
  console.log(this.name + " is driven with " + this.wheels + " wheels" );
}


要将车辆作为drive()值调用this

var vehicle1 = new vehicle("Bike", 2);
drive.call(vehicle1);


.call()的第一个参数将用作被调用函数中this的值。

09-13 09:30