0

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

小提琴

4

1 回答 1

3

您错过了 onClick 是在 Button 的原型上定义的事实,并且您没有在 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 片段工作得很好。

于 2013-05-03T11:45:31.680 回答