I've seen this question and I know how to extend a class. However, is it good practice to do that with a method? Is it safe to use this:
function extendClass(child, parent) {
child.prototype = Object.create(parent.prototype);
child.constructor = child;
}
extendClass(Banana, Fruit);
instead of this:
Banana.prototype = Object.create(Fruit.prototype);
Banana.prototype.constructor = Banana;
Using functions to perform repeated work rather than repeating the work everywhere you need to do it is standard practice. It leads to reduced opportunity for error and centralizes the operation in case it needs enhancing over time. There's nothing special about hooking up constructor functions and associated prototypes ("classes") in an inheritance relationship that makes it an exception.
Tangentially-related side note: As of ES2015 (aka "ES6", the spec released in June 2015) this way of setting up those hierarchies is outdated (though of course it still works). The ES2015+ way is class
and extends
.