Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Static super references in JavaScript
// Simulated static super references (as proposed by the current draft of the ECMAScript 6 specification)
//------------------ Library
function inherits(subC, superC) {
var subProto = Object.create(superC.prototype);
// At the very least, we keep the "constructor" property
// At most, we preserve additions that have already been made
copyOwnFrom(subProto, subC.prototype);
setUpHomeObjects(subProto);
subC.prototype = subProto;
};
function ssuper(func) {
return Object.getPrototypeOf(func.__homeObject__);
}
function setUpHomeObjects(obj) {
Object.getOwnPropertyNames(obj).forEach(function(key) {
var value = obj[key];
if (typeof value === "function" && value.name === "me") {
value.__homeObject__ = obj;
}
});
}
function copyOwnFrom(target, source) {
Object.getOwnPropertyNames(source).forEach(function(propName) {
Object.defineProperty(target, propName,
Object.getOwnPropertyDescriptor(source, propName));
});
return target;
};
//------------------ Example
// Super-constructor
function Person(name) {
this.name = name;
}
Person.prototype.describe = function() {
return "Person called "+this.name;
};
// Sub-constructor
var Employee = function me(name, title) {
ssuper(me).constructor.call(this, name);
this.title = title;
}
Employee.prototype.describe = function me() {
return ssuper(me).describe.call(this)+" ("+this.title+")";
};
inherits(Employee, Person);
var jane = new Employee("Jane", "CTO");
console.log(jane.describe()); // Person called Jane (CTO)
@rauschma

This comment has been minimized.

Copy link
Owner Author

rauschma commented Nov 15, 2011

Simulating dynamic super references is more complicated: https://gist.github.com/1331748

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.