Multiple inheritance using classes

前端 未结 4 1243
小蘑菇
小蘑菇 2020-12-11 14:15

Is it possible to extend only some specific part from multiple classes? Example:

4条回答
  •  囚心锁ツ
    2020-12-11 14:53

    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.

提交回复
热议问题