0

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;
Community
  • 1
  • 1
dodov
  • 5,206
  • 3
  • 34
  • 65
  • I think they're the same. The first one is more flexible in case you have to extend a lot of classes (so you won't write those two lines of code for each class) – ibrahim mahrir Jan 29 '17 at 13:40

1 Answers1

3

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Is it also alright to call `extendClass(Banana, Fruit)` _before_ I declare the actual `Banana` function? The declaration should be hoisted on top and things would work fine, right? – dodov Jan 29 '17 at 13:52
  • 2
    @HristiyanDodov: Provided it's a function declaration and not a function expression, it would work, yes, because (as you say) of hoisting. Whether you want to do that as a matter of style is up to you, of course. – T.J. Crowder Jan 29 '17 at 13:53
  • CF. *"this way of setting up those hierarchies is outdated"*. The only thing that is *perceived* as being outdated is the *syntax* to set up those hierarchies. The ES2015 "way" does exactly the same while hiding the true nature of the class, a prototype, and adding some extra pitfalls (e.g. no real private methods or properties). – webketje Jan 29 '17 at 15:43
  • @Tyblitz: No, it's not exactly the same; the new syntax can do things the old can't (like subclass Error and Array). I don't think it hides anything, but whatever. Certainly doesn't impact the things you can do to make things private; same techniques continue to apply. – T.J. Crowder Jan 29 '17 at 15:48
  • @T.J.Crowder Everything that can be done with the new syntax can be done with ES5, but not vice-versa (e.g. `class` constructor function cannot be used with `.call` or `.apply`). I'm leaving it at that, and if you really think it doesn't hide anything, Eric Elliott has a [good series about all the pitfalls of ES6 classes](https://medium.com/search?q=es6%20classes%20eric%20elliott). – webketje Jan 29 '17 at 16:25