I am learning the basics of OOP in Javascript and came across an inheritance example which is difference than what I’ve typically seen.
Typical:
ChildClass.prototype = new ParentClass();
Alternate Method:
function clone(object) {
function OneShotConstructor(){}
OneShotConstructor.prototype = object;
return new OneShotConstructor();
}
SecondClass.prototype = clone(FirstClass.prototype);
Why would the latter be preferred when creating an object whose prototype is another object?
Because you will invoke the constructor of the custom type (a.k.a. class) you are trying to inherit from. And that might have side effects. Imagine the following:
Your counter has been incremented, but you didn’t really create a useful instance of ParentClass.
Another problem, is that all instance properties (see
this.options) will be present on ChildClass’ prototype, and you probably don’t want that.Note: When using constructor, you might have instance properties, and shared properties. For example: