CoffeeScript将对象添加到数组

时间:2012-09-02 14:26:00

标签: javascript arrays object coffeescript scoping

我有以下代码:

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

numbers的{​​{1}}数组应该包含2个seq对象,其值为1和2,但我得到的结果是2和2 ...有人可以让我失望吗?光?

2 个答案:

答案 0 :(得分:1)

使用@来声明本地字段。

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

答案 1 :(得分:1)

问题是您的编号类会复制到以下JavaScript。变量号存储在范围内而不是Number函数的成员:

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;

})();

您必须使用@将要存储的号码设为该类的属性:

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

编译为:

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;

})();