【问题标题】:I try to pass my function from my first and second object into new function which take arguments of first and second object我尝试将我的函数从我的第一个和第二个对象传递到新函数中,该函数接受第一个和第二个对象的参数
【发布时间】:2021-05-13 14:37:19
【问题描述】:

var myHonda = {
  color: 'red',
  wheels: 4,
  engine: {
    cylinders: 4,
    size: 2.2
  },
  distance: 40,
  time: 1,
  speed: function(distance, time) {
    distance = this.distance;
    time = this.time;
    console.log(distance / time);
    // console.log(`Current speed is ${this.distance * this.time} `);
  }

};

var myHonda2 = {
  color: 'red',
  wheels: 4,
  engine: {
    cylinders: 4,
    size: 2.2
  },
  distance: 20,
  time: 2,
  speed: function(distance, time) {
    distance = this.distance;
    time = this.time;
    console.log(distance / time + "kmph");
  }

};

let displaySpeed = function(myObject) {
  console.log(`Speed of Car is ${myObject.speed}`);
}

displaySpeed(myHonda);
displaySpeed(myHonda2);

【问题讨论】:

标签: javascript function object


【解决方案1】:

如果您正在设置函数参数的值,您可能不需要将它们作为函数参数传递。

speed: function() {
   const distance = this.distance
   const time = this.time
   return distance / time
}

只是我注意到的一件事,您可能还需要调用 speed myObject.speed() - 这将返回 distance / time

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 2011-03-08
    • 2021-12-20
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多