I have been reading a lot lately about some core concepts of JS and inheritance is a bit confusing.
Here are the methods that I know of:
// Base class
function Parent(foo) {
if (foo === undefined) {
throw new TypeError('foo is undefined');
}
this.foo = foo;
}
// Derived class
function Child(foo, bar) {
if (foo === undefined) {
throw new TypeError('foo is undefined');
}
if (bar === undefined) {
throw new TypeError('bar is undefined');
}
Parent.call(this, foo);
this.bar = bar;
}
1. Using a temporary function
function tmpFn(){}
tmpFn.prototype = Parent.prototype;
Child.prototype = new tmpFn();
Child.prototype.constructor = Child;
2. Using a Parent
instance
Child.prototype = new Parent(); // fail
Child.prototype = new Parent(null); // hax
Child.prototype.constructor = Child;
3. Using Object#create
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
After examining the prototype chains for all methods, I realised that they all yield the same result (which is kind of obvious). But in all these methods, there's one thing that's common. We are creating a third object to replace the prototype and then re-set the constructor. are two overrides involved:-
Child.prototype = ...
Child.prototype.constructor = Child
This got me thinking: Why not simply do Child.prototype.__proto__ = Parent.prototype
?
Or a safer alternative, Object.setPrototypeOf(Child.prototype, Parent.prototype)
.
What's the harm in this?