Last active
December 13, 2015 20:58
-
-
Save darkoverlordofdata/4973587 to your computer and use it in GitHub Desktop.
Insert a new base class in the prototype chain. Taken from "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/getPrototypeOf".
This file contains hidden or 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
# | |
# 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