在课堂上使用nextTick

use*_*104 0 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 process context
Run Code Online (Sandbox Code Playgroud)

它不起作用,因为process.nextTick将我们带入了一个不同的上下文,其中没有定义@someAttr.我该如何解决这个问题(当我想调用SomeClass的方法时)?

Joh*_*mew 5

通常的方法是将一个引用存储this在一个局部变量中,该变量将在匿名函数中可用.在JavaScript中:

function someFunction() {
  var self = this;
  process.nextTick(function() {
    self.someAttr = true;
  });
}
Run Code Online (Sandbox Code Playgroud)

CoffeeScript有一个特殊的语法来帮助解决这个问题." 胖箭 ":

class SomeClass:
  someFunction: ->
    process.nextTick =>
      @someAttr = true
Run Code Online (Sandbox Code Playgroud)