Skip to content

Instantly share code, notes, and snippets.

@revolunet
Last active March 4, 2019 22:56
Show Gist options
  • Save revolunet/8415007 to your computer and use it in GitHub Desktop.
Save revolunet/8415007 to your computer and use it in GitHub Desktop.
Basic javascript prototypal inheritance example demonstrating instantiation, inheritance and superclasses calls
function Animal(name) {
this.name = name;
}
Animal.prototype.breathe = function(animal) {
console.log('animal breathe : ' + this.name);
};
Animal.prototype.die = function() {
console.log('animal die : ' + this.name);
};
function Human() {
// apply the super constructor to this
Animal.apply(this, arguments);
}
// by default, inherit all super properties & methods
Human.prototype = new Animal();
// override some method
Human.prototype.breathe = function(human) {
console.log('human breathe', this.name);
Object.getPrototypeOf(Human.prototype).breathe.call(this);
// call the parent. equivalent to :
// Animal.prototype.breathe.call(this);
};
function SuperHero() {
// apply the super constructor to this
Human.apply(this, arguments);
}
// by default, inherit all super properties & methods
SuperHero.prototype = new Human();
SuperHero.prototype.breathe = function(superhero) {
console.log('superhero breathe', this.name);
Object.getPrototypeOf(SuperHero.prototype).breathe.call(this);
// equivalent to :
// Human.prototype.breathe.call(this);
};
// override a method
SuperHero.prototype.die = function() {
console.log('No luck, SuperHero never dies :)', this.name);
};
console.log('-----');
console.log('create animal');
var a = new Animal('popy');
console.log(a, a.name);
a.breathe();
console.log('-----');
console.log('create human');
var b = new Human('jul');
console.log(b, b.name);
b.breathe();
console.log('-----');
console.log('create SuperHero');
var c = new SuperHero('ironman');
console.log(c, c.name);
c.breathe();
console.log('-----');
a.die();
b.die();
c.die();
@bloodyowl
Copy link

 Object.getPrototypeOf(Human.prototype).breathe.call(this);

I'd stay with

Animal.prototype.breathe.apply(this, arguments)

for maximum compatibility.

Human.prototype = new Animal();

as this.name is set, we can see unwanted behaviour :

var inherit = Object.create || function(object){
  function F(){}
  F.prototype = object
  return new F()
}

and

Human.prototype = inherit(Animal.prototype)

@revolunet
Copy link
Author

thanks a ton !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment