Last Updated: February 25, 2016
· dperrymorrow

Easily Extend Javascript Prototypes

So you have a class in javascript and you want it to inherit from another class right?

You want the following

  • to be able to call the parent class constructor as well as the child
  • you want the child class to inherit all methods from the parent class
  • you want to be able to call super on individual methods in the child class

If so, keep reading....

simple utility function for extending a class

function extend (base, constructor) {
  var prototype = new Function();
  prototype.prototype = base.prototype;
  constructor.prototype = new prototype();
  constructor.prototype.constructor = constructor;

Example parent class in this case Animal that has a name and makes noise

// parent class
function Animal (name) {
  this.animalName = name;
  console.log("////== Animal Constructor ==/////");
  console.log("An animal named " + name);

Animal.prototype.makeNoise = function (noise) {
  console.log("////== Animal makeNoise() ==////");
  console.log(noise + ", I can make noise...");

Ok, now we want to make a Dog class that inherits from Animal

function Dog (name) {
  // call the super, name);
  console.log("////== Dog Constructor ==/////");
  console.log("I am a Dog named " + this.animalName);

// important that this happens before you override methods on parent class
extend(Animal, Dog);

Dog.prototype.makeNoise = function (noise) {, noise);
  console.log("////== Dog makeNoise() ==////");
  console.log("I am a Dog, I like to " + noise);

So we now have a Dog that also has all the Animal methods. We would use it like so...

var dog = new Dog("Sparky");

And that would output

"////== Animal Constructor ==/////"
"An animal named Sparky"
"////== Dog Constructor ==/////"
"I am a Dog named Sparky"
"////== Animal makeNoise() ==////"
"Bark!!, I can make noise..."
"////== Dog makeNoise() ==////"
"I am a Dog, I like to Bark!!"

See example working,console

3 Responses
Add your response

Just to add on this, if you happen to be on node.js there's already a builtin function for this (util.inherits):

over 1 year ago ·

I found that Object.create is somewhat easier to handle.

over 1 year ago ·

yeah nice examples, thanks!

over 1 year ago ·