Inheritance 如何创建具有自己属性的CoffeeScript子类

Inheritance 如何创建具有自己属性的CoffeeScript子类,inheritance,coffeescript,subclass,Inheritance,Coffeescript,Subclass,我正在尝试在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"

我正在尝试在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: #{@}"
问题是: 但是,Foo类的实例并没有维护自己的items属性副本

预期结果: JSFIDLE
为方便起见

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

必须在构造函数中初始化数组,才能为每个实例初始化单独的数组

试一试


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

必须在构造函数中初始化数组,才能为每个实例初始化单独的数组

试一试

还记得在Foo:s构造函数中调用super。还记得在Foo:s构造函数中调用super。
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 :(​
b = new Foo()   # []
b.add(5)        # [5]
class List
  constructor: ->
    @items = []