Created
September 29, 2014 08:41
-
-
Save Hotell/b81fd3fad6e614645400 to your computer and use it in GitHub Desktop.
js inheritance
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
// 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