将范围保持在Async.js中
鉴于Coffeescript中的以下课程:
class MyClass extends events.EventEmitter someObj: null # set somewhere during constructor someMethod: () -> async.parallel([ @task1, @task2, @task3, ], (err, results) -> doSomething() task1: (callback) -> @someObj.funnyMethod() # fails callback() );
最后一行的@someObj.funnyMethod()
调用失败:
TypeError: Cannot read property 'funnyMethod' of undefined
显然, this
是指callback中的上下文。 对于正常的callback,我已经学会了使用胖箭头操作符=>
而不是瘦->
。
用async.js(或者其他类似的库)处理这个干净的方法是什么?
您可以使用task1
定义中的胖箭头:
task1: (callback) =>
但是,我不会推荐它。 方法的胖箭头与函数的胖箭头完全不同,并且具有性能惩罚。
你可能想要的是将这些函数的绑定版本传递给async.parallel
。 你可以用Function::bind
或匿名的胖箭头函数来做到这一点:
@task1.bind(@), # Function::bind => @task2(), # anonymous function