Skip to content

Instantly share code, notes, and snippets.

@qickstarter
Created September 19, 2012 04:56
Show Gist options
  • Select an option

  • Save qickstarter/3747750 to your computer and use it in GitHub Desktop.

Select an option

Save qickstarter/3747750 to your computer and use it in GitHub Desktop.
# Polymorphism
class String
add :(value)->
alert "string add #{value}"
class Number
add :(value)->
alert "number add #{value}"
class Array
add :(value)->
alert "array add #{value}"
# create Demo
class Demo
add : (value...) ->
return undefined unless @isValid(value)
# create instance
instance = null
switch typeof value[0]
when 'string'
instance = new String
when 'number'
instance = new Number
when 'object'
instance = new Array
instance.add(value)
isValid : (value) ->
return if value[0]? then true else false
demo = new Demo
demo.add("0") #=> string add 0
demo.add(0) #=> number add 0
demo.add(["0"]) #=> array add 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment