咖啡脚本中的嵌套方法

Nested methods in coffescript

本文关键字:嵌套 方法 脚本 咖啡      更新时间:2023-09-26

作为下面的示例,我希望将方法嵌套到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()

我发现的唯一方法是

  1. 克隆我的嵌套方法对象
  2. 将每个嵌套方法绑定到我的当前对象

我宁愿将其保留在我的原型对象中,以避免在创建新对象时重新创建所有嵌套方法。我在这里找到了答案,但我没有找到处理它的好方法。我也找到了答案,这是唯一的方法吗?

感谢您的帮助

如果你做函数而不是对象,你可以跟踪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()