0
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?

2
  • A constructor can't return anything. An instance of the class is always returned when you instantiate a class. Doesn't have anything to do with your question but I thought I should let you know. Commented Apr 9, 2012 at 13:02
  • Correction for others reading along … constructors absolutely can return values; they simply must return an object (that is, no primitive values, such as numbers or strings.) (See: es5.github.io/#x13.2.2, steps 9. and 10.) Commented Apr 15, 2013 at 23:55

1 Answer 1

3

This is a scoping problem: $.each accepts a function, which has it's on scope, thus, your this variable is not the one you expected.

The working code:

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

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

What changed? Check the arrow on the $.each call, 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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.