ES6 中的子类和继承


在 JavaScript 中,开发者在 ES5 中使用原型来继承函数。在 ES6 中,JavaScript 中引入的类可以像其他编程语言一样用于继承。

什么是子类和继承?

顾名思义,子类是另一个类的子类。我们可以使用继承从超类创建或派生子类,我们可以将类称为派生该类的超类,并将子类称为派生类。

子类包含超类所有属性和方法,我们可以使用子类对象访问它们。可以使用“extends”关键字从超类派生类。

语法

您可以按照以下语法从超类继承子类。

Class superClass {
   // members and methods of the superClass
}
class subClass extends superClass {
   // it contains all members and methods of the superclass
   // define the properties of the subclass
}

我们在上面的语法中使用了 class 关键字来创建类。此外,用户可以看到我们如何使用 extends 关键字从 superClass 继承 subClass。

继承的优点

在我们继续本教程之前,让我们了解继承的不同优点。

  • 继承允许我们重用超类的代码。

  • 继承节省时间,因为我们不需要经常编写相同的代码。

  • 此外,我们可以使用继承生成具有适当结构的可维护代码。

  • 我们可以使用继承覆盖超类方法,并在子类中再次实现它们。

让我们通过现实生活中的例子来理解继承。这样我们可以更好地理解继承。

示例

在下面的示例中,我们创建了 house 类。Two_BHK 类继承了 house 类,这意味着 Two_BHK 类包含 house 类所有属性和方法。

我们覆盖了 house 类的 get_total_rooms() 方法,并在 Two_BHK 类中实现了它们自己的方法。

Open Compiler
<html> <body> <h2>Using the <i> extends </i> keyword to inherit classes in ES6 </h2> <div id = "output"> </div> <script> let output = document.getElementById("output"); class house { color = "blue"; get_total_rooms() { output.innerHTML += "House has a default room. </br>"; } } // extended the house class via two_BHK class class Two_BHK extends house { // new members of two_BHK class is_galary = false; // overriding the get_total_rooms() method of house class get_total_rooms() { output.innerHTML += "Flat has a total of two rooms. </br>"; } } // creating the objects of the different classes and invoking the //get_total_rooms() method by taking the object as a reference. let house1 = new house(); house1.get_total_rooms(); let house2 = new Two_BHK(); house2.get_total_rooms(); </script> </body> </html>

现在,您可以理解继承的实际用途。您可以在上面的示例中观察我们如何使用继承重用代码。此外,它提供了上面示例演示的清晰结构。此外,我们可以在超类中定义方法的结构,并在子类中实现它。因此,超类提供了清晰的方法结构,我们可以在子类中实现它们。

示例

在这个例子中,我们使用了类的构造函数来初始化类的属性。此外,我们使用了 super() 关键字从子类调用超类的构造函数。

请记住,在初始化子类的任何属性之前,需要在子类构造函数中编写 super() 关键字。

Open Compiler
<html> <body> <h2>Using the <i> extends </i> keyword to inherit classes in ES6 </h2> <div id = "output"> </div> <script> let output = document.getElementById("output"); // creating the superclass class superClass { // constructor of the super-class constructor(param1, param2) { this.prop1 = param1; this.prop2 = param2; } } // Creating the sub-class class subClass extends superClass { // constructor of subClass constructor(param1, param2, param3) { // calling the constructor of the super-class super(param1, param2); this.prop3 = param3; } } // creating the object of the subClass let object = new subClass("1000", 20, false); output.innerHTML += "The value of prop1 in the subClass class is " + object.prop1 + "</br>"; output.innerHTML += "The value of prop2 in subClass class is " + object.prop2 + "</br>"; output.innerHTML += "The value of prop3 in subClass class is " + object.prop3 + "</br>"; </script> </body> </html>

在本教程中,我们学习了继承。此外,本教程还教我们如何在子类中覆盖方法,以及如何从子类调用超类的构造函数来初始化所有超类属性。

更新于:2023年1月17日

315 次查看

开启你的职业生涯

完成课程获得认证

开始学习
广告