您好,欢迎访问一九零五行业门户网

解释ES6中的子类和继承

在 javascript 中,开发人员使用原型来继承 es5 中的另一个函数。在es6中,javascript中引入的类可以像其他编程语言一样用于继承。
什么是子类和继承?正如子类一词所代表的那样,它是另一个类的子类。我们可以使用继承来从超类创建或派生子类,并且可以将类调用为超类,从中派生出类,将子类调用为派生类。
子类包含了超类的所有属性和方法,我们可以使用子类对象来访问它。您可以使用“extend”关键字从超类派生该类。
语法您可以按照以下语法从超类继承子类。
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关键字从超类继承子类。
继承的好处在继续本教程之前,让我们先了解继承的不同好处。
继承允许我们重用超类的代码。
继承可以节省时间,因为我们不需要经常编写相同的代码。
此外,我们可以使用继承生成具有适当结构的可维护代码。
我们可以使用继承来重写超类方法,并在子类中再次实现它们。
让我们通过现实生活中的例子来理解继承。这样我们就可以正确理解继承了。
示例在下面的示例中,我们创建了 house 类。 two_bhk 类继承了 house 类,也就是说 two_bhk 类包含了 house 类的所有属性和方法。
我们重写了 house 类的 get_total_rooms() 方法,并在 two_bhk 类中实现了自己的方法。
<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() 关键字。
<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>
我们在本教程中学习了继承。此外,本教程还教我们重写子类中的方法并从子类调用超类的构造函数来初始化所有超类属性。
以上就是解释es6中的子类和继承的详细内容。
其它类似信息

推荐信息