我有以下代码:
class Example
@text = 'Hello world! ;)'
getText = ->
@text
constructor: ->
alert(getText())
### Instance ###
example = new Example
这将返回“未定义”,有什么办法让它返回@text
内容吗?
最佳答案
这是 CoffeeScript 中的一个常见错误。查看编译后的 JavaScript:
Example = (function() {
var getText;
Example.text = 'Hello world! ;)';
getText = function() {
return this.text;
};
function Example() {
alert(getText());
}
return Example;
})();
在类定义中使用@
创建静态方法或变量。也就是说,它附加到类对象。
如果您尝试将其设为实例变量,请在构造函数中将其设置。
constructor: ->
@text = 'Hello world! ;)'
alert(getText())
如果您尝试访问静态属性,请参阅类名称。
getText = ->
Example.text
关于javascript - 使用 CoffeeScript 在 "public variable"中获取 "private method",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17893420/