the problem is I don't see a difference, when we want to establish an inheritance, between these 2 methods:
Child.prototype = Object.create( Father.prototype );
Child.prototype.constructor = Child;
and:
Child.prototype.__proto__ = Father.prototype;
The first option allows us to get all the properties and methods that our Father is sharing but overwriting the Child constructor in the process. That's what we need to set the Child constructor back to Child again. The second method does the same but without the overwriting. So, why people/Guides don't use the second option? Am I wrong in anything?
This is a complete example:
function Father( name ) {
this.name = name;
}
Father.prototype.getName = function() {
console.log( this.name );
}
function Child( name, lastName ) {
Father.call( this, name );
this.lastName = lastName;
}
Child.prototype.__proto__ = Father.prototype;
//Child.prototype = Object.create( Father.prototype );
//Child.prototype.constructor = Child;
var c = new Child( 'Will' , 'Travolta');
c.getName();
I don't see a difference between these 2 methods
There is no difference in the outcome indeed (apart from minor details such as the enumerability of the .constructor
property).
So, why people/Guides don't use the second option?
Because __proto__
is deprecated, while Object.create
works about anywhere. It was standardised with ES5 and can easily be polyfilled for older environments.
Since ES6, you could also use Object.setPrototypeOf
, but since ES6, you'd just write class Child extends Father { … }
.