1

As the following example , I would like to have nested methods into coffescript class (or native js).

class Child
  constructor: (@id) ->
    console.log "new child #{@id}"
  animations:
    start: ->
      console.log @, "#{@id} start animation"
    custom:
      rotate: ->
        console.log @, "#{@id} custom rotate animation"

class Parent
  constructor: ->
    @_childs = []
    _.each [1..10], (index) =>
      @_childs.push new Child(index)
  startAll: ->
    _.each @_childs, (child) ->
      child.animations.start()


parent = new Parent()
parent.startAll()

The only way I found, is to

  1. Clone my nested methods object
  2. Bind each nested methods to my current object

I'd rather keep it into my prototype object, in order to avoid to recreate all the nested methods when I create a new object. I found an answer here, but I didn't find a nice way to deal with it. I also found the answer, is it the only way to do it ?

Thx for your help

Community
  • 1
  • 1
Frédéric GRATI
  • 805
  • 1
  • 6
  • 19
  • Best thing is not to use nested methods, it's a pain to keep track of `this`. I'd just namespace the method in the function's name, like `animationStart`. – elclanrs Jan 27 '15 at 09:14
  • I understand your point of view and you are probably right, but I find this a little sad to say "In javascript, it's a pain to keep track of 'this' so let's just change the method name" :( – Frédéric GRATI Jan 27 '15 at 09:38

1 Answers1

1

If you make functions instead of objects you can keep track of this:

class Child
  constructor: (@id) ->
    console.log "new child #{@id}"
  animations: ->
    start: =>
      console.log @, "#{@id} start animation"
    custom: ->
      rotate: =>
        console.log @, "#{@id} custom rotate animation"

Then just call the function, that will return an object.

child.animations().start()
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • You are right, I definitively can do that. I will just wait some minutes before accepting your answer, in order to see if somebody has another answer :) Thx a lot anyway – Frédéric GRATI Jan 27 '15 at 09:59