-
-
Save sandywu/1409478 to your computer and use it in GitHub Desktop.
Static super references in JavaScript
This file contains 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 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