prototype-property-vs-assigment-form
by Glenn Dwiyatcita
JavaScript
/**
* Parent class.
*/
function Animal(name) {
this.name = name;
};
Animal.prototype.breath = function () {
console.log(this.name + ' is breathing.');
};
/**
* Child class using the "property" form.
*/
function Bird(name) {
Animal.call(this, name);
};
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
Bird.prototype.fly = function () {
console.log(this.name + ' is flying.');
};
console.dir(Bird);
/**
* Child class using the "assignment" form.
*/
function Mammal(name) {
Animal.call(this, name);
}
Mammal.prototype = Object.create(Animal.prototype);
Mammal.prototype = { // this assignment will wipe out the prototype.__proto__ property (breaking the prototype chain)
constructor: Mammal,
walk: function () {
console.log(this.name + ' is walking.');
}
};
console.dir(Mammal);
/**
* Child class using the "assignment" form (with __proto__).
*/
function Fish(name) {
Animal.call(this, name);
}
Fish.prototype = {
__proto__: Animal.prototype, // connecting the chain manually
constructor: Fish,
swim: function () {
console.log(this.name + ' is swimming.');
}
};
console.dir(Fish);
var birdy = new Bird('Birdy')
, glenn = new Mammal('Glenn')
, nemo = new Fish('Nemo');
birdy.breath();
birdy.fly();
nemo.breath();
nemo.swim();
glenn.breath(); // The code breaks here 'cause Glenn cannot breath.
glenn.walk();