Could you explain me why necessary (or recommended) to use “__proto__” and “prototype” in JavaScript inheritance? Here are two code examples and it seems that their result is exactly the same with and without using of prototype. The result is the following in both cases:
"elephant is walking to melbourne"
"sparrow is walking to sydney"
"sparrow is flying to melbourne"
Example one:
function Animal(name) {
this.name = name;
}
Animal.prototype.walk = function (destination) {
console.log(this.name, 'is walking to', destination);
};
var animal = new Animal('elephant');
animal.walk('melbourne');
function Bird(name) {
Animal.call(this, name);
}
Bird.prototype.__proto__ = Animal.prototype;
Bird.prototype.fly = function (destination) {
console.log(this.name, 'is flying to', destination);
}
var bird = new Bird('sparrow');
bird.walk('sydney');
bird.fly('melbourne');
Example two:
function Animal(name) {
this.name = name;
this.walk = function (destination) {
console.log(this.name, 'is walking to', destination);
};
}
var animal = new Animal('elephant');
animal.walk('melbourne');
function Bird(name) {
Animal.call(this, name);
this.fly = function (destination) {
console.log(this.name, 'is flying to', destination);
}
}
var bird = new Bird('sparrow');
bird.walk('sydney');
bird.fly('melbourne');
For example why "Bird.prototype.fly = function..." is better than simple "this.fly = function..." in Bird function?