2016-11-30 9 views
-2

変数名が "@"記号で始まる場合、Coffeescriptではどういう意味ですか? 例えば、私は私がCoffeescript "@"変数

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 

が、私はそれのいくつかの他の場所を見てきました、hubotのソースコードを通って、ちょうど私が見てきた最初の数行で見てきたが、私はそうではありませんそれが何を意味するのかを推測できました。

+1

coffeescript @はこれを意味します。 – HelloSpeakman

+1

[CoffeeScriptのドキュメント](http://coffeescript.org)を見ましたか? '@'を検索することであなたの質問に答えることができ、おそらく他にもいくつかのことを教えてくれるでしょう。 –

答えて

2

シンボルは、Operators and Aliasesのようにthisのショールカットです。

this.propertyのショートカットとして、@propertyを使用できます。

0

基本的に、 "@"変数はクラスのインスタンス変数、つまりクラスメンバーです。静的メンバーと比較できるクラス変数と混同しないでください。

また、あなたはOOP言語のthisまたはself演算子として@variablesと考えることができますが、それは昔のjavascript thisとまったく同じものではありません。そのjavascript thisは現在のスコープを参照しています。これはコールバック内のクラススコープを参照しようとするときにいくつかの問題を引き起こします。そのためcoffescriptは@variablesを導入しています。 @、これらの日は、あなたがクラスのインスタンス(すなわち、thisまたはself)を参照していることを意味し、

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); 
    }); 
} 

決勝の思考:

はたとえば、次のコードを検討してください。したがって、@dataは基本的にはthis.dataを意味するので、@がなければ、範囲内の可視変数dataを参照します。

関連する問題