Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active April 8, 2018 02:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rauschma/1367052 to your computer and use it in GitHub Desktop.
Save rauschma/1367052 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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