Skip to content

Instantly share code, notes, and snippets.

@darkoverlordofdata
Last active December 13, 2015 20:58
Show Gist options
  • Save darkoverlordofdata/4973587 to your computer and use it in GitHub Desktop.
Save darkoverlordofdata/4973587 to your computer and use it in GitHub Desktop.
#
# Object.addSuper
#
# @see Object.getPrototypeOf
#
__addSuper = (object, prototype) ->
# wrap primitive values
object = (if object instanceof Object then object else new object.constructor(object))
# follow the thread to the base prototype
current = next = object.__proto__
while (current isnt Object::) and (current isnt Function::)
next = current
current = next.__proto__
if prototype.constructor is Function
prototype.__proto__ = object
object = prototype
prototype = Function::
next.__proto__ = prototype
object
# First example: appending a chain to a prototype
class Mammal
constructor: ->
@isMammal = "yes"
class MammalSpecies extends Mammal
constructor: (sMammalSpecies) ->
super
@species = sMammalSpecies
oCat = new MammalSpecies("Felis")
console.log oCat.isMammal # yes
class Animal
constructor: ->
@breathing = "yes"
__addSuper oCat, new Animal()
console.log oCat.breathing # yes
# Second example: transforming a primitive value into an instance of its constructor and append its chain to a prototype
class Symbol
constructor: ->
@isSymbol = "yes"
nPrime = 17
console.log typeof nPrime # number
oPrime = __addSuper(nPrime, new Symbol())
console.log oPrime # {}
console.log oPrime.isSymbol # yes
console.log typeof oPrime # object
console.log oPrime.valueOf() # 17
# Third example: appending a chain to the Function.prototype object and appending a new function to that chain
class Person
constructor: (sName) ->
@identity = sName
george = __addSuper(new Person("George"), -> console.log("Hello guys!!"))
console.log george.identity # "George"
george() # "Hello guys!!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment