JavaScript:重构对象中的方法和函数存在问题

JavaScript: Issues with methods and functions in refactored object

第一次问!

我重构的方法(以前在对象内部的方法)不再识别它们与对象的关系...如何让这些方法起作用?

我正在尝试对此对象(汽车)应用移动和加速功能。 move_fn 线性增加汽车的位置 (1, 2, 3, 4... n)。 acc_fn 通过将汽车先前的速度增加与其当前位置相加(30mph + 2 位置 = 32mph、32mph + 3 位置 = 35mph、35mph + 4 位置 = 39mph 等),以指数方式增加汽车的加速度。此外,function_runner 同时运行这两种方法,使一切按顺序开始:

var move_fn = function(){
  var prev_position = this.position
  this.position += + 1
  console.log(this.type + " is moving from " + prev_position + " to " + 
  this.position + '.')
}

var spd_fn = function(){
  var prev_speed = this.speed
  console.log(this.position)
  this.speed += this.position
  console.log(this.type + ' is accelerating from ' + prev_speed + ' to ' +
  this.speed + '.' )
}

var function_runner = function(){
  this.move_fn()
  this.acc_fn()
}

var car = {
  type: 'Honda CRV',
  position: 1,
  speed: 30,
  move: move_fn,
  speed: spd_fn,
  fn_run: function_runner
}


car.function_runner()

Car 不再有名为 function_runner 的方法,您已将其分配给 fn_run 方法,因此您将调用 car.fn_run()。与 move_fn 相同 - 重命名为移动,并且 "acc_fn" 未在任何地方定义。

所以会是:

var move_fn = function(){
  var prev_position = this.position
  this.position += + 1
  console.log(this.type + " is moving from " + prev_position + " to " + 
  this.position + '.')
}

var spd_fn = function(){
  var prev_speed = this.speed
  console.log(this.position)
  this.speed += this.position
  console.log(this.type + ' is accelerating from ' + prev_speed + ' to ' +
  this.speed + '.' )
}

var function_runner = function(){
  this.move()
  this.speed()
}

var car = {
  type: 'Honda CRV',
  position: 1,
  speed: 30,
  move: move_fn,
  speed: spd_fn,
  fn_run: function_runner
}

car.fn_run()

...虽然这是一种奇怪的结构方式。