2016-11-30 56 views
-2

變量名稱以「@」符號開頭時,Coffeescript中的含義是什麼? 例如,我一直在尋找通過hubot源代碼,只是在第幾行,我看了一下,我發現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 

我已經看到了其他幾個地方,但我沒有能夠猜出它的意思。

+1

在coffeescript @意味着這一點。 – HelloSpeakman

+1

你看過[CoffeeScript文檔](http://coffeescript.org)嗎?搜索「@」可以回答你的問題,也可能教你一些其他的東西。 –

回答

2

@符號是this的shorcut,如在Operators and Aliases中所見。

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

0

它基本上意味着「@」變量是類的實例變量,也就是類成員。這不應該和類變量混淆,你可以比較靜態成員。

而且,你能想到的@variables作爲thisself運營商OOP語言,但它不是完全一樣的事情如舊的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