1

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?

2 Answers 2

1

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;

})();
Sign up to request clarification or add additional context in comments.

Comments

1

Use @ for declare local fields.

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

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()

2 Comments

That works. I have 2 follow up questions though: 1. When you use constuctor: (@num) ->, would that make the variable public? I can now access to the value num outside of the class by calling Number.num. Is there any way to keep the variable private and the only way to access to the num value is through getNumber method? 2. What was my problem?
@TríNguyễn: There is no private in JavaScript so there is no private in CoffeeScript. You can have private at the class level though.

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.