我正在尝试在 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
为您提供方便的代码片段