Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop nextTick在类中的用法_Oop_Node.js_Coffeescript - Fatal编程技术网

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