1

我正在尝试在 CoffeeScript 中做一些简单的子类化

class List
  items: []
  add: (n) ->
    @items.push(n)
    console.log "list now has: #{@}"

  toString: ->
    @items.join(', ')

class Foo extends List
  constructor: ->
    console.log "new list created"
    console.log "current items: #{@}"

问题:

a = new Foo() # []
a.add(1)      # [1]
a.add(2)      # [2]

b = new Foo() # [1,2]
# why is b initializing with A's items?

b.add(5)      # [1,2,5]
# b is just adding to A's list :(​

但是,Foo类的实例不维护它们自己的items属性副本。

预期结果:

b = new Foo()   # []
b.add(5)        # [5]

jsFiddle

为您提供方便的代码片段

4

1 回答 1

4

您正在为 List 的原型设置数组,该数组与 List 的所有实例共享。

您必须在构造函数中初始化数组,以便为​​每个实例初始化单独的数组。

尝试

class List
  constructor: ->
    @items = []
于 2012-09-10T16:29:29.943 回答