Skip to content

Instantly share code, notes, and snippets.

@lmartins
Last active August 29, 2015 13:57
Show Gist options
  • Save lmartins/9859753 to your computer and use it in GitHub Desktop.
Save lmartins/9859753 to your computer and use it in GitHub Desktop.
Extend Objects with CoffeeScript
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