Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
157 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

class Walker {
  constructor() {}
  walk() {
    console.log("I am walking");
  }
  // more functions
}

class Runner {
  constructor() {}
  run() {
    console.log("I am running");
  }
  // more functions
}

class Participant {
  constructor() {}
}

// add methods from other classes to the Participant class
Participant.prototype.run = Runner.prototype.run;
Participant.prototype.walk = Walker.prototype.walk;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...