Coffeescript “咖啡脚本”@&引用;变量
在Coffeescript中,变量名以“@”符号开头意味着什么? 例如,我一直在查看hubot的源代码,在我查看的前几行中,我发现Coffeescript “咖啡脚本”@&引用;变量,coffeescript,Coffeescript,在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) -
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
我在其他几个地方见过它,但我猜不出它的意思。它基本上意味着“@”变量是类的实例变量,即类成员。不要将其与类变量混淆,您可以将其与静态成员进行比较 此外,您可以将
@variables
视为OOP语言的this
或self
操作符,但这与旧的javascriptthis
并不完全相同。javascriptthis
引用当前作用域,这会在尝试引用回调中的类作用域时导致一些问题,例如,这就是为什么coffescript引入了@变量来解决此类问题的原因
例如,考虑下面的代码:
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);
});
}
最后,现在的@
意味着您引用的是类实例(即this
或self
)。因此,@data
基本上是指此.data
,因此,如果没有@
,它将引用范围内的任何可见变量data
。@
符号是此
的符号,如中所示
作为此.property
的快捷方式,您可以使用@property
在coffeescript中@的意思是这样的。你看过?搜索@
将回答您的问题,并可能教会您一些其他东西。