Oop nextTick在类中的用法
如果我有这样的代码:Oop nextTick在类中的用法,oop,node.js,coffeescript,Oop,Node.js,Coffeescript,如果我有这样的代码: 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
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将我们带入一个不同的上下文中,其中没有定义@somettr。如何解决这个问题(也是在我想调用某个类的方法时)?通常的解决方法是将对
this
的引用存储在一个局部变量中,该变量将在匿名函数中可用。在JavaScript中:
function someFunction() {
var self = this;
process.nextTick(function() {
self.someAttr = true;
});
}
CoffeeScript有一个特殊的语法来帮助实现这一点;“:
通常的解决方法是将对
this
的引用存储在一个局部变量中,该变量将在匿名函数中可用。在JavaScript中:
function someFunction() {
var self = this;
process.nextTick(function() {
self.someAttr = true;
});
}
CoffeeScript有一个特殊的语法来帮助实现这一点;“:
使用
=>
而不是->
来保留此变量
class SomeClass
constructor: =>
@someAttr = false
someFunction: ->
process.nextTick =>
@someAttr = true
使用=>
而不是->
来保留此变量
class SomeClass
constructor: =>
@someAttr = false
someFunction: ->
process.nextTick =>
@someAttr = true