I have the following code:
class Number
number = null
constructor: (num) ->
number = num
getNumber: -> number
class Sequence
numbers = []
constructor: ->
addNumber: (n) ->
numbers.push new Number n
displaySequence: ->
for number in numbers
alert number.getNumber()
seq = new Sequence()
seq.addNumber 1
seq.addNumber 2
seq.displaySequence()
The numbers array of seq should contains 2 Number object with value 1 and 2, but the result I’m getting is 2 and 2… Can someone shed me some light?
The problem is your number class which copiles to the following JavaScript. Where the variable number is stored in the scope instead of being member of the Number function:
You have to make the number you wanna store to be a property of the class using
@:which compiles to: