使用类的多重继承 [英] Multiple inheritance using classes

查看:163
本文介绍了使用类的多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从多个类扩展一些特定的部分?例如:

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

推荐答案

只要您的新对象具有实例数据和方法,您可以从其他类中选择要添加到现有类中的方法正在添加期望在该对象上。

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.

这篇关于使用类的多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆