CoffeeScript mixin不起作用

时间:2013-05-03 11:21:44

标签: coffeescript

我在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

1 个答案:

答案 0 :(得分:3)

你错过了在Button的原型上定义onClick的事实, 并且您没有在include函数

中使用正确的顺序设置参数
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片段效果非常好。