class Example
constructor: ->
$.each [1, 2, 3], (key, value) ->
@test = value
return @test
render: ->
alert @test
example = new Example()
example.render()
I’m using CoffeeScript (+ jQuery) and this is an class example where I would get the value 3 in @test variable. But this does not happen, can you help me?
This is a scoping problem:
$.eachaccepts a function, which has it’s on scope, thus, yourthisvariable is not the one you expected.The working code:
What changed? Check the arrow on the
$.eachcall, it’s now a fat arrow. Fat arrows does the trick of setting a _this variable and using it when you use@...making your scope the one you expected to be.Check http://coffeescript.org on the section “Function Binding” for more details!