Coffeescript“@”变量

Coffeescript "@" variables

在 Coffeescript 中,变量名以“@”符号开头是什么意思? 例如,我一直在查看 hubot 源代码,在我查看的前几行中,我发现

class Brain extends EventEmitter
  # Represents somewhat persistent storage for the robot. Extend this.
  #
  # Returns a new Brain with no external storage.
    constructor: (robot) ->
    @data =
      users:    { }
      _private: { }

    @autoSave = true

    robot.on "running", =>
      @resetSaveInterval 5

我在其他几个地方也看到过,但一直猜不出来是什么意思。

基本意思是“@”变量是class的实例变量,即class成员。这不会与 class 变量混淆,您可以将其与静态成员进行比较。

此外,您可以将 @variables 视为 OOP 语言的 thisself 运算符,但它与旧的 javascript 并不完全相同 this。 javascript this 指的是当前范围,例如,当您尝试在回调中引用 class 范围时,这会导致一些问题,这就是为什么 coffescript 引入了 @variables,解决此类问题。

例如,考虑以下代码:

Brain.prototype = new EventEmitter();

function Brain(robot){

  // Represents somewhat persistent storage for the robot. Extend this.
  //
  // Returns a new Brain with no external storage.

    this.data = {
      users:    { },
      _private: { }
    };

    this.autoSave = true;    

    var self = this;

    robot.on('running', fucntion myCallback() {
      // here is the problem, if you try to call `this` here
      // it will refer to the `myCallback` instead of the parent
      // this.resetSaveInterval(5);
      // therefore you have to use the cached `self` way
      // which coffeescript solved using @variables
      self.resetSaveInterval(5);
    });
}

最后的想法是,如今的 @ 意味着您指的是 class 实例(即 thisself)。因此,@data 基本上意味着 this.data,因此,如果没有 @,它将引用范围内的任何可见变量 data

@ 符号是 this 的快捷方式,您可以在 Operators and Aliases.

中看到

As a shortcut for this.property, you can use @property.