Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
* If you want to extend your ES5 objects with less ceremony, here's a function you can use to make your
* life a little easier. I originally included this in the post, but added too much information and
* not enough clarity. This may not be the best way to solve our problem, but it illuminates the process
* of automating inheritance to abstract it from your logic.
*
* This accompanies the blog post: http://www.chrisstead.com/archives/705/mainstay-monday-inheritance/
*/
function extends(child, parent){
var childPrototype = child.prototype, // Stores a pointer
childPrototypeKeys = Object.keys(childPrototype);
child.prototype = Object.create(parent.prototype);
child.prototype.constructor = child;
childPrototypeKeys.forEach(function(key){
child.prototype[key] = childPrototype[key];
});
}
/*
* Once our logic is abstracted away, our inheritance looks like this. You'll note that all of a sudden
* our code goes back to the more familiar, unencumbered ES5 style we have all come to understand.
*/
function Greeter(){}
Greeter.prototype = {
greet: function(name){
console.log('Hello, ' + name + '.');
},
fooGreet: function(){
this.greet(this.foo());
}
};
extends(Greeter, Fooer);
/*
* Just like in the blog post, we can see the use of our object produces
* the inheritance characteristics we have come to expect.
*/
var myGreeter = new Greeter();
myGreeter.greet('Chris'); // log: Hello, Chris.
myGreeter.foo(); // bar
myGreeter.fooGreet(); // log: Hello, bar.
myGreeter instanceof Greeter; // true
myGreeter instanceof Fooer; // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment