【问题标题】:How to use 'Function.prototype.call' to invoke a function that is not attached to prototype of any object如何使用“Function.prototype.call”调用未附加到任何对象原型的函数
【发布时间】:2017-10-04 12:22:54
【问题描述】:

以下代码的输出是undefined has undefined wheels,而不是Bike has 2 wheelsInstantiated 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 

【问题讨论】:

  • vehicle 函数中,您需要使用this.... 定义这些变量,例如:this.name = "car"
  • 您的车辆构造函数应该执行this.name = ... 将变量附加到实例。您只是在声明隐式全局变量。
  • 我还是明白了,car has 4 wheels
  • @Prem 你修复了你的构造函数,使它服从传递的参数,而不是硬编码“car”和 4?
  • @Prem:显然,你没有。请仔细阅读Pointy's answermine

标签: javascript


【解决方案1】:

很遗憾,您的代码几乎所有内容都不正确。

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

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

那么,你的函数“drive”应该不带任何参数:

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

使用您的车辆作为this 值调用drive()

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

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

【讨论】:

    【解决方案2】:

    几个问题:

    1. 您将vehicle 用作构造函数,但未将任何属性分配给this

    2. 您没有在vehicle 中使用namewheels 参数

    3. 您将namewheels 参数定义为drive,但在调用它时不使用它们并且不提供它们。

    4. 不是真正的问题,只是约定(正如我在your last question 中提到的那样):如果您打算将newvehicle 一起使用,最初应该设置上限:Vehicle压倒性约定。

    见 cmets:

    var vehicle = function(name, wheels){
      // Actually use name and wheels and put them on `this`
      this.name = name;
      this.wheels = wheels;
    }; // <== Added missing ;
    
    function drive(/* No parameters here*/) {
    	console.log(this.name + " is driven with " + this.wheels + " wheels" );
    }
    
    var vehicle1 = new vehicle('Bike' , 2);
    drive.call(vehicle1);

    【讨论】:

      【解决方案3】:

      你需要像这样使用this

      var vehicle = function(name, wheels){
      	this.name = "car",
      	this.wheels = 4,
      	this.fuel = "petrol"
      }
      
      function drive(name, wheels) {
      	console.log(this.name + " is driven with " + this.wheels + " wheels" );
      }
      
      var vehicle1 = new vehicle('Bike' , 2);
      drive.call(vehicle1); //undefined is driven with undefined wheels 

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-13
        • 2020-06-09
        • 2012-12-20
        • 2010-10-07
        • 2012-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多