Last active
April 8, 2018 02:25
-
-
Save rauschma/1367052 to your computer and use it in GitHub Desktop.
Static 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
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simulating dynamic super references is more complicated: https://gist.github.com/1331748