Is it possible to extend only some specific part from multiple classes? Example:
class Walker {
walk() {
console.log("I am walking");
}
// more functions
}
class Runner {
run() {
console.log("I am running");
}
// more functions
}
// Make a class that inherits only the run and walk functions
Use composition:
You can pick and choose which methods from other classes you want to add to an existing class as long as your new object has the instance data and methods that the methods you are adding expect to be on that object.
Keep in mind that methods are just functions that are properties on the prototype. So, you can assign any functions to the prototype that you want as long as the object you put them on has the right supporting instance data or other methods that those newly added methods might need.
Of course, if we understood more of your overall problem, you may also be able to solve your problem with more classical inheritance, but you can't use inheritance to solve it the exact way you asked to solve it.
Standard inheritance inherits all the methods of the base class. If you just want some of them, you will have to modify the prototype object manually to put just the methods you want there.
In the future, you will get a better set of answers if you describe the problem you're trying to solve rather than the solution you're trying to implement. That lets us understand what you're really trying to accomplish and allows us to offer solutions you haven't even thought of yet.
Having a look on the provided example, I immediately would suggest "... please consider decomposition."
For the given code it was extracting both behaviors "walk" and "run". Thus a
Walker
might end up as a hypotheticalPerson
withWalkingAbility
, aRunner
then likewise becomes aPerson
withRunningAbility
. All the// more functions
within the originally providedWalker
andRunner
code then could be implemented by aPerson
class.A first big win was that one now is in control of where to place the composition, either at
prototype
level or within theconstructor
. It depends on aWalker
's /Runner
's final design and can be answered best by the OP her/himself.... versus ...
Another win of decomposing behavior into smaller or even atomic "composable units of reuse"[^1] comes from the easiness of composing them again into bigger tailored mixins/traits like ...
[^1]: SCG, University of Bern: »Talents: Dynamically Composable Units of Reuse«
Note ... there is now a second part of this answer providing the example from above again, but with a real trait approach backed by a library
Note ... I had to split my previous answer into 2 separate parts since for quite a while it is not anymore that easy referencing outside hosted javascript code. Due to that I now do provide the necessary trait library as minified inline code within the next given example ...
Having on hand natively implemented Talents or Traits one day in JavaScript, will make this kind of composition even more flexible/powerful ...