Ethan McTague
Ethan McTague

Reputation: 2358

Class child functions refer to parent

I have written the following code:

class TheClass
  children: []
  addChild: (argone, argtwo) ->
    pos = @children.push new TheClass argone, argtwo
    @children[pos - 1]
  iterateChildren: ->
    console.log @children
    for child in @children
      child.iterateChildren()
  constructor: (@argone, @argtwo) ->

a = new TheClass 1,1
b = a.addChild 2,2
c = a.addChild 3,3
ba = b.addChild 4,4
ca = c.addChild 5,5
a.iterateChildren()

The class has one function to add a child object, and one function to iterate over it's children, telling them to do the same.

Unlike my expectations, this code repeatedly calls the iterateChildren() method of itself, instead of that of it's children, resulting in a's children array being printed infinitely.

What did I do wrong, and how might I fix this?

Upvotes: 0

Views: 19

Answers (1)

mu is too short
mu is too short

Reputation: 434685

Properties declared in the class definition are attached the prototype, not each individual instance. That means that this:

class TheClass
  children: []

only creates one children array that will be shared by all instances. So your class is more or less equivalent to this:

children_array_for_everyone = [ ]
class TheClass
  addChild: (argone, argtwo) ->
    pos = children_array_for_everyone.push new TheClass argone, argtwo
    @children[pos - 1]
  iterateChildren: ->
    console.log children_array_for_everyone
    for child in children_array_for_everyone
      child.iterateChildren()
  constructor: (@argone, @argtwo) ->

If you want each instance to have its own @children (and you do want this), then create the array in the constructor:

class TheClass
  # No children here
  #...
  constructor: (@argone, @argtwo) ->
    @children = [ ]

Upvotes: 1

Related Questions