得到"公共变量“;在“;私有方法”;使用CoffeeScript

Getting "public variable" in a "private method" using CoffeeScript

本文关键字:有方法 使用 CoffeeScript 变量 quot 得到      更新时间:2023-09-26

我有以下代码:

class Example
  @text = 'Hello world! ;)'
  getText = ->
    @text
  constructor: ->
    alert(getText())
### Instance ###
example = new Example

这将返回"undefined",有什么方法可以让它返回@text内容吗?

http://jsfiddle.net/vgS3y/

这是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