在coffeescript中缺乏隐含的这一点

时间:2012-08-06 17:18:20

标签: coffeescript

这是我的coffeescript代码。

class Hello
  constructor: ->
    @greetings()
    this.greetings()
    greetings()

  greetings: ->
    alert 'hello world'

new Hello

此代码转换为

var Hello;

Hello = (function() {

  function Hello() {
    this.greetings();
    this.greetings();
    greetings();
  }

  Hello.prototype.greetings = function() {
    return alert('hello world');
  };

  return Hello;

})();

new Hello;

在coffeescript代码的第三种情况下,我既没有使用@也没有使用this。我假设coffeescript会使用隐含的,但似乎并非如此。

我做了一个快速的谷歌搜索,但没有得到任何结果。所以任何人都可以确认coffeescript不支持暗示这一点。

1 个答案:

答案 0 :(得分:4)

Coffeescript不支持隐式this。主要是因为咖啡脚本实际上只是javascript的糖,而在javascript中,这将是一个非常糟糕的主意,因为函数是第一类对象,可以分配给局部变量。

那么如何访问局部变量?

a = -> 123
@a = -> 456

// normal coffeescript
a() # 123

// with implicit this
a() # 123 or 456? Impossible to know.

重要的是要记住,在java脚本var a;this.a之间没有任何关系,并且总是2个独立的变量。知道何时解决哪个问题非常重要。

最后,这就是创建@符号的原因。在javascript中使用基于类的样式时,在所有地方引用this的{​​{1}}属性变得非常常见。当以这种方式编程时,this.propName被添加到咖啡脚本中会变得不那么乏味和恼人。