Mulan
Mulan

Reputation: 135197

How to create CoffeeScript subclass with its own properties

I am trying to do some simple subclassing in 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: #{@}"

The problem:

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 :(​

However, instances of Foo class are not maintaining their own copy of the items property.

Expected Result:

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

jsFiddle

code snippet provided for your convenience

Upvotes: 1

Views: 640

Answers (1)

esamatti
esamatti

Reputation: 18944

You are setting the array for the prototype of the List which is shared with all instances of List.

You must initialize the array in the constructor in order to initialize separate arrays for each instance.

Try

class List
  constructor: ->
    @items = []

Upvotes: 4

Related Questions