Skip to content

Instantly share code, notes, and snippets.

@rauschma
Created November 1, 2011 20:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rauschma/1331748 to your computer and use it in GitHub Desktop.
Save rauschma/1331748 to your computer and use it in GitHub Desktop.
Semi-dynamic super references in JavaScript
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"
@rauschma
Copy link
Author

The static version is much prettier: https://gist.github.com/1367052

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment