我在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'
答案 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()
所以mixin片段效果非常好。