我有以下代码:
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 ...有人可以让我失望吗?光?
答案 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;
})();