Last active
August 29, 2015 13:57
-
-
Save lmartins/9859753 to your computer and use it in GitHub Desktop.
Extend Objects with CoffeeScript
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
extend = (target) -> | |
return unless arguments[1] | |
for property in arguments | |
sourceProp = property | |
for prop of sourceProp | |
if not target[prop] and sourceProp.hasOwnProperty(prop) | |
target[prop] = sourceProp[prop] | |
return | |
Person = (name) -> | |
@name = name | |
Dog = (name) -> | |
@name = name | |
speaker = | |
speak: -> | |
"#{@name} is speaking" | |
mover = | |
walk: -> | |
"#{@name} is walking" | |
run: -> | |
"#{@name} is running" | |
arithmetic = | |
add: -> | |
"#{@name} is adding numbers together" | |
multiply: -> | |
"#{@name} is multiplying numbers together" | |
extend(Person::, speaker, mover, arithmetic) | |
extend(Dog::, speaker, mover) | |
john = new Person "John Doe" | |
fido = new Dog "Fido" | |
fido.walk() | |
john.walk() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment