Last Updated: February 25, 2016
·
6.787K
· david morrow

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
  Animal.call(this, 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) {
  Animal.prototype.makeNoise.call(this, 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");
dog.makeNoise("Bark!!");

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
http://jsbin.com/zixohimo/1/edit?js,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): http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

over 1 year ago ·

I found that Object.create is somewhat easier to handle. https://gist.github.com/dmi3y/64d0808d7a137a874934

over 1 year ago ·

yeah nice examples, thanks!

over 1 year ago ·