【问题标题】:CoffeeScript mixin doesn't workCoffeeScript mixin 不起作用
【发布时间】:2013-05-03 19:45:31
【问题描述】:

我在 coffeescript faq 中找到了这个 mixins 示例,但它似乎不起作用。

我错过了什么吗?

extend = (obj, mixin) ->
  for name, method of mixin
    obj[name] = method

include = (klass, mixin) ->
  extend klass.prototype, mixin

class Button
  onClick: -> alert "click"

class Events
include Button, Events

(new Events).onClick()

# => Uncaught TypeError: Object #<Events> has no method 'onClick' 

fiddle

【问题讨论】:

    标签: coffeescript


    【解决方案1】:

    您错过了 onClick 是在 Button 的原型上定义的事实, 并且您没有在包含函数中以正确的顺序设置参数

    extend = (obj, mixin) ->
      for name, method of mixin
        obj[name] = method
    
    include = (klass, mixin) ->
      extend klass.prototype, mixin
    
    class Button
      onClick: -> alert "click"
    
    class Events
    include Events,Button.prototype
    
    (new Events).onClick()
    

    see the "fiddle"

    所以 mixin sn-p 工作得很好。

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 2016-12-02
      • 2018-08-27
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多