Created
January 24, 2012 17:20
-
-
Save jarek-foksa/1671263 to your computer and use it in GitHub Desktop.
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
# "Framework" | |
Object.define = (arg) -> | |
prototype = arg.__prototype__ || Object.prototype | |
object = Object.create prototype | |
for property of arg | |
if arg.hasOwnProperty property | |
object[property] = arg[property] | |
delete object.__prototype__ | |
return object | |
# | |
# Prototypical inheritance | |
# | |
animal = Object.define | |
__prototype__: Object.prototype | |
init: (name) -> | |
@name = name | |
return @ | |
move: (meters) -> | |
console.log "#{@name} moved #{meters} m." | |
snake = Object.define | |
__prototype__: animal | |
move: -> | |
animal.move.apply @, arguments | |
console.log "Slithering..." | |
horse = Object.define | |
__prototype__: animal | |
move: -> | |
animal.move.apply @, arguments | |
console.log "Galloping..." | |
sam = Object.create(snake).init("Sammy the Python") | |
tom = Object.create(horse).init("Tommy the Palomino") | |
sam.move 10 | |
tom.move 120 | |
# | |
# Classical inheritance | |
# | |
class Animal | |
constructor: (@name) -> | |
move: (meters) -> | |
alert @name + " moved #{meters}m." | |
class Snake extends Animal | |
move: -> | |
alert "Slithering..." | |
super 5 | |
class Horse extends Animal | |
move: -> | |
alert "Galloping..." | |
super 45 | |
sam = new Snake "Sammy the Python" | |
tom = new Horse "Tommy the Palomino" | |
sam.move() | |
tom.move() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment