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。但这并没有发生,你能帮助我吗?
最佳答案
这是一个范围界定问题:
$.each
接受一个函数,该函数在作用域内,因此,您的 this
变量不是您期望的变量。
工作代码:
class Example
constructor: ->
$.each [1, 2, 3], (key, value) =>
@test = value
return @test
render: ->
alert @test
example = new Example()
example.render()
什么改变了?检查 $.each
调用上的箭头,它现在是一个粗箭头。粗箭头的技巧是设置一个 _this 变量,并在使用 @...
时使用它,使您的作用域成为您期望的作用域。
检查http://coffeescript.org有关更多详细信息,请参阅“函数绑定(bind)”部分!
关于javascript - CoffeeScript 类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10073309/