Last active
December 10, 2015 23:08
-
-
Save jkarmel/4506733 to your computer and use it in GitHub Desktop.
CoffeeScript Mixin Class. Extend it to create mixin functionality.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Mixin | |
@mixin: (Klass)-> | |
# Class methods | |
Klass[key] = val for key, val of @ when key != 'mixin' | |
# Instance methods | |
Klass::[key] = val for key, val of @prototype | |
class Extra extends Mixin | |
@fn: -> alert 'class fn called' | |
fn: -> alert 'instance fn called' | |
class Base | |
baseClassFn: -> 'baseClassFn called' | |
baseInstancefn: -> 'baseInstanceFn called' | |
Extra.mixin Base | |
Base.fn() #'class fn' alerted | |
b = new Base | |
b.fn() #'instance fn' alerted | |
# Also, you can use this right in the class definition! | |
class Base2 | |
Extra.mixin @ | |
baseClassFn: -> 'baseClassFn called' | |
baseInstancefn: -> 'baseInstanceFn called' | |
Base2.fn() #'class fn' alerted | |
b2 = new Base2 | |
b2.fn() #'instance fn' alerted |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment