0
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。但这不会发生,你能帮帮我吗?

4

1 回答 1

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 arrows 可以设置一个 _this 变量,并在您使用@...使您的范围成为您期望的范围时使用它。

有关更多详细信息,请查看“功能绑定”部分的http://coffeescript.org !

于 2012-04-09T12:49:54.193 回答