Search code examples
javascriptarraysobjectcoffeescriptscoping

CoffeeScript Adding object to an array


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?


Solution

  • 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:

    Number = (function() {
      // number is stored in the scope not as a member of the prototype
      var number;
    
      number = null;
    
      // this is the function that will be return
      // so when ever you call it you override number
      function Number(num) {
        number = num;
      }
    
      Number.prototype.getNumber = function() {
        return number;
      };
    
      return Number;
    
    })();
    

    You have to make the number you wanna store to be a property of the class using @:

    class Number
     constructor: (@num) ->
     getNumber: -> @num
    

    which compiles to:

    var Number;
    
    Number = (function() {
    
      function Number(num) {
        //now num is stored in the returned function not in the scope of the parent function
        this.num = num;
      }
    
      Number.prototype.getNumber = function() {
        return this.num;
      };
    
      return Number;
    
    })();