Created
November 1, 2011 20:07
-
-
Save rauschma/1331748 to your computer and use it in GitHub Desktop.
Semi-dynamic super references in JavaScript
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
function A() { | |
} | |
A.prototype.desc = function() { | |
return "A"; | |
} | |
function B() { | |
} | |
B.prototype = Object.create(A.prototype); | |
B.prototype.desc = function() { | |
return "B" + this.super("desc"); | |
} | |
function C() { | |
} | |
C.prototype = Object.create(B.prototype); | |
C.prototype.desc = function() { | |
return "C" + this.super("desc"); | |
} | |
Object.prototype.super = function (method) { | |
// here: the object where the method making the super-call is located | |
var hereKey = "__here_"+method; | |
var oldHere = this[hereKey]; | |
var start = Object.getPrototypeOf( | |
oldHere ? oldHere : findObjectOfProperty(this, method) // where is the current method? | |
); | |
var here = findObjectOfProperty(start, method); | |
this[hereKey] = here; | |
var result = here[method](); | |
if (oldHere) { | |
this[hereKey] = oldHere; | |
} else { | |
delete this[hereKey]; | |
} | |
return result; | |
} | |
function findObjectOfProperty(start, propName) { | |
while(true) { | |
if (!start) { | |
throw Error("Could not find property "+propName); | |
} | |
if (start.hasOwnProperty(propName)) { | |
return start; | |
} | |
start = Object.getPrototypeOf(start); | |
} | |
} | |
console.log(new C().desc()); // "CBA" | |
console.log(C.prototype.desc()); // "CBA" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The static version is much prettier: https://gist.github.com/1367052