2013-05-03 31 views
0

我在coffeescript faq中发现了这个mixin的例子,但它似乎不起作用。CoffeeScript mixin不起作用

我在这里错过了什么吗?

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

回答

3

你缺少的事实的onClick是按键, 的原型定义,你没有用正确的顺序设置的参数中包括功能

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片段工作得很好。

相关问题