Skip to content

Instantly share code, notes, and snippets.

@sandywu
Forked from rauschma/static_super.js
Created November 30, 2011 15:29
Show Gist options
  • Save sandywu/1409478 to your computer and use it in GitHub Desktop.
Save sandywu/1409478 to your computer and use it in GitHub Desktop.
Static super references in JavaScript
// Simulated static super references (as proposed by Allen Wirfs-Brock).
// http://wiki.ecmascript.org/doku.php?id=harmony:object_initialiser_super
//------------------ 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);
addSuperReferencesTo(subProto);
subC.prototype = subProto;
};
function addSuperReferencesTo(obj) {
Object.getOwnPropertyNames(obj).forEach(function(key) {
var value = obj[key];
if (typeof value === "function" && value.name === "me") {
value.super = Object.getPrototypeOf(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) {
me.super.constructor.call(this, name);
this.title = title;
}
Employee.prototype.describe = function me() {
return me.super.describe.call(this)+" ("+this.title+")";
};
inherits(Employee, Person);
var jane = new Employee("Jane", "CTO");
console.log(jane.describe()); // Person called Jane (CTO)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment