Last active
March 4, 2019 22:56
-
-
Save revolunet/8415007 to your computer and use it in GitHub Desktop.
Basic javascript prototypal inheritance example demonstrating instantiation, inheritance and superclasses calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'd stay with
for maximum compatibility.
as
this.name
is set, we can see unwanted behaviour :and