【问题标题】:Coffeescript "@" variablesCoffeescript "@" 变量
【发布时间】:2016-12-01 15:35:44
【问题描述】:

当变量名以“@”符号开头时,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

我在其他几个地方见过它,但我无法猜出它的含义。

【问题讨论】:

  • 在coffeescript中@表示这个。
  • 你看过CoffeeScript documentation吗?搜索 @ 会回答您的问题,并且可能还会教您一些其他的东西。

标签: coffeescript


【解决方案1】:

@ 符号是this 的快捷方式,如您在Operators and Aliases 中所见。

作为this.property 的快捷方式,您可以使用@property

【讨论】:

    【解决方案2】:

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

    此外,您可以将@variables 视为OOP 语言的thisself 运算符,但它与旧的javascript this 不完全相同。 javascript this 指的是当前作用域,这会在你试图在回调中引用类作用域时导致一些问题,这就是为什么 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);
        });
    }
    

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

    【讨论】:

      猜你喜欢
      • 2011-12-27
      • 2012-01-20
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 2014-09-20
      • 2014-08-29
      • 2012-03-10
      • 2016-04-11
      相关资源
      最近更新 更多