【发布时间】: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