Skip to content

Instantly share code, notes, and snippets.

@Hotell
Created September 29, 2014 08:41
Show Gist options
  • Save Hotell/b81fd3fad6e614645400 to your computer and use it in GitHub Desktop.
Save Hotell/b81fd3fad6e614645400 to your computer and use it in GitHub Desktop.
js inheritance
// Person super class
function Person(name) {
this.name = name;
}
Person.prototype.describe = function () {
return 'Person called '+this.name;
};
// Employee sub class
function Employee(name, title) {
Employee._super.constructor.call(this, name);
this.title = title;
}
Employee.prototype.describe = function () {
return Employee._super.describe.call(this)+' ('+this.title+')';
};
// inheritance
subclasses(Employee, Person);
// usage
var jane = new Employee('Jane', 'CTO');
jane.describe();
/**
*
*/
function subclasses(SubC, SuperC) {
var subProto = Object.create(SuperC.prototype);
// Save `constructor` and, possibly, other methods
copyOwnPropertiesFrom(subProto, SubC.prototype);
SubC.prototype = subProto;
SubC._super = SuperC.prototype;
}
/**
* (1) Get an array with the keys of all own properties of source.
* (2) Iterate over those keys.
* (3) Retrieve a property descriptor.
* (4) Use that property descriptor to create an own property in target.
*
* Note that this function is very similar to the function _.extend() in the Underscore.js library.
*/
function copyOwnPropertiesFrom(target, source) {
Object.getOwnPropertyNames(source) // (1)
.forEach(function(propKey) { // (2)
var desc = Object.getOwnPropertyDescriptor(source, propKey); // (3)
Object.defineProperty(target, propKey, desc); // (4)
});
return target;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment