CoffeeScript类变量

时间:2012-04-09 12:40:14

标签: javascript class variables coffeescript

class Example
  constructor: ->
    $.each [1, 2, 3], (key, value) ->
      @test = value
    return @test
  render: ->
    alert @test

example = new Example()
example.render()​​​​​​​​​​​​​​​​​​​​​​

我正在使用CoffeeScript(+ jQuery),这是一个类示例,我将在@test变量中获得值3。但这不会发生,你能帮助我吗?

1 个答案:

答案 0 :(得分:3)

这是一个范围问题: $.each接受一个函数,该函数包含在范围内,因此,您的this变量不是您预期的变量。

工作代码:

class Example
  constructor: ->
    $.each [1, 2, 3], (key, value) =>
      @test = value
    return @test
  render: ->
    alert @test

example = new Example()
example.render()​​​​​​​​​​​​​​​​​​​​​​

改变了什么?检查$.each电话上的箭头,它现在是一个胖箭头。 Fat arrow可以设置一个_this变量,并在你使用@...时使用它,使你的范围成为你期望的范围。

检查“功能绑定”部分的http://coffeescript.org以获取更多详细信息!