如果我有这样的代码:
class SomeClass
constructor: ->
@someAttr = false
someFunction: ->
process.nextTick ->
@someAttr = true
obj = new SomeClass
obj.someFunction()
obj.someAttr # Would still be false, because the @ (this) is in the process context
这是行不通的,因为process.nextTick将我们带入了另一个未定义@someAttr的上下文。我该如何解决(也当我想调用SomeClass的方法时)?
最佳答案
解决此问题的常用方法是将对this
的引用存储在本地变量中,该变量将在匿名函数中可用。在JavaScript中:
function someFunction() {
var self = this;
process.nextTick(function() {
self.someAttr = true;
});
}
CoffeeScript具有特殊的语法来帮助解决此问题。 “ fat arrow”:
class SomeClass:
someFunction: ->
process.nextTick =>
@someAttr = true