在JavaScript中,OOP(面向对象编程)中的”super”的作用是:

huangapple go评论76阅读模式
英文:

The role of super in OOP in JS

问题

super()用于调用父类的构造函数。问题是为什么我们需要调用父类的构造函数?我们为什么要关心这个?

英文:

I was learning OOP in JS and came across super() which is used to invoke the constructor of parent class. The question is Why do we need to call the constructor of parent class? Just why do we care?

答案1

得分: 3

构造函数执行一些操作。这些操作的具体内容取决于类的类型。

如果你正在创建一个子类,那么大多数情况下,你会想要执行相同的操作。可能还需要做一些额外的事情。

与其复制粘贴父类的构造函数然后编辑它(这将要求你手动保持两个函数的同步,如果其中一个发生更改),我们使用super()来调用它。

英文:

The constructor does stuff. What that stuff is depends on what the class is.

If you are creating a subclass then, most of the time, you will want to do the same stuff. Possibly with some extra things too.

Rather than copy/pasting the constructor function from the parent class and then editing it (which would require that you manually keep both functions in sync with each other if either changed) we use super() to call it instead.

答案2

得分: 0

super在父子类之间维护连接。当像super.myParentMethod()这样使用它时,它只调用在直接父类或更上层声明的myParentMethod

当在子类的constructor中调用它时,它将调用父类的constructor,因此父类将在子类之前初始化。

要完全理解为什么需要它,您可能需要更多了解JS中的类和构造函数。

这有一篇非常好的文章介绍了这个主题。

英文:

Basically, super kind of maintains the connection between parent & child classes. When it's used like super.myParentMethod() it just calls myParentMethod declared in direct parent class or upper the road.

When it is called in the constructor of a child, it will call parent's constructor, so, the parent will be initialized before child is.

To fully understand why it's needed, you probably need to learn more about classes & constructor functions in JS.

There's an extremely good article about this topic.

huangapple
  • 本文由 发表于 2020年1月3日 22:20:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580151.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定