Skip to content

Instantly share code, notes, and snippets.

@Acconut
Last active December 17, 2015 00:19
Show Gist options
  • Save Acconut/5520378 to your computer and use it in GitHub Desktop.
Save Acconut/5520378 to your computer and use it in GitHub Desktop.
Inheritances in JavaScript

Simple inheritance

All properties are inherited but the constructor can't be overwritten:

function A() {}

A.prototype.foo = function() {
  return "foo";
};

var B = A;

var b = new B();
b.foo(); // foo

var C = A;

C.prototype.foo = function() {
  return "bar";
};

var c = new C();
c.foo(); // bar

Extending the parent

Using this solution you can extend the parent and overwrite the contructor, too:

function extend(parent, newConst) {
  
  var super_ = newConst || parent.constructor || function() {};
  
  for(var i in parent.prototype) {
    super_.prototype[i] = parent.prototype[i];
  }
  
  return super_;
    
}

function Animal(name) {
  this.name = name;
  console.log("A new animal is born");
}

Animal.prototype.walk = function() {
  console.log(this.name + " is walking");
};

var Horse = extend(Animal, function(name) {
  if(name) this.name = name;
  console.log("A new horse is born");
});

var bob = new Horse("Bob"); // A new horse is born
bob.walk(); // Bob is walking

Multiple inheritance

function Animal(name) {
  this.name = name;
  console.log("A new animal is born");
}

Animal.prototype.walk = function() {
  console.log(this.name + " is walking");
};

var FastAnimal = extend(Animal);
FastAnimal.prototype.walk = function() {
  console.log(this.name + " is running not walking");
};

var Horse = extend(FastAnimal, function(name) {
  if(name) this.name = name;
  console.log("A new horse is born");
});

var bob = new Horse("Bob"); // A new horse is born
bob.walk(); // Bob is running not walking
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment