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

JavaScript: Issues with methods and functions in refactored object

本文关键字:函数 存在 问题 方法 重构 对象 JavaScript      更新时间:2023-09-26

第一次询问!

我的重构方法(以前在对象内部的方法(不再识别它们与对象的关系。。。我该如何让这些东西发挥作用?

我正在尝试将移动和加速功能应用于这个物体(汽车(。move_fn线性地增加汽车的位置(1、2、3、4…n(。acc_fn通过将汽车先前的速度增加与当前位置相加(30英里/小时+2位置=32英里/小时,32英里/小时+3位置=35英里/小时、35英里/小时+4位置=39英里/小时等(,使汽车的加速度呈指数级增加。此外,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也是如此-重命名为move,并且"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()

尽管这是一种奇怪的结构方式。