作为following example,我想将嵌套方法放入coffescript类(或本机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()
我发现的唯一方法是
答案 0 :(得分:1)
如果您使用函数而不是对象,则可以跟踪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"
然后只需调用该函数,它将返回一个对象。
child.animations().start()