【问题标题】:JavaScript: Issues with methods and functions in refactored objectJavaScript:重构对象中的方法和函数的问题
【发布时间】:2015-11-08 10:10:03
【问题描述】:

第一次问!

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

我正在尝试对这个对象(汽车)应用移动和加速功能。 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()

【问题讨论】:

    标签: javascript methods refactoring javascript-objects


    【解决方案1】:

    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()
    

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

    【讨论】:

    • 我还有两个名为“速度”的属性,这把事情搞砸了。在您的帮助和更多的修补下,它又开始工作了!谢谢!
    猜你喜欢
    • 2021-02-28
    • 1970-01-01
    • 2023-04-09
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多