做我的狗漫画网站,icp备案系统网站,唯品会网站页面设计,经典软文案例100例简短在JavaScript中#xff0c;使用class关键字可以实现面向对象编程。其中#xff0c;extends和super是两个非常重要的关键字#xff0c;它们分别用于实现类的继承和调用父类的方法。
一、extends关键字
extends关键字用于实现类的继承#xff0c;它可以让一个子类继承父类的…在JavaScript中使用class关键字可以实现面向对象编程。其中extends和super是两个非常重要的关键字它们分别用于实现类的继承和调用父类的方法。
一、extends关键字
extends关键字用于实现类的继承它可以让一个子类继承父类的属性和方法。使用extends关键字时需要指定要继承的父类语法如下
class 子类 extends 父类 {// 子类的属性和方法
}例如定义一个Person类和一个Student类Student类继承自Person类
class Person {constructor(name, age) {this.name name;this.age age;}sayHello() {console.log(Hello, my name is ${this.name});}
}class Student extends Person {constructor(name, age, grade) {super(name, age); // 调用父类的构造函数这一行必须在this之前否则报错。因为子类自己的this对象必须先通过父类的构造函数完成塑造得到与父类同样的实例属性和方法然后再对其进行加工添加子类自己的实例属性和方法。如果不调用super()方法子类就得不到自己的this对象。this.grade grade;}study() {console.log(Im studying...);}
}在上面的例子中Student类继承了Person类的构造函数和方法并且定义了自己的属性和方法。在构造函数中使用super关键字来调用父类的构造函数以便初始化父类的属性和方法。 注意 上面的super(name, age)必须在this之前。因为子类自己的this对象必须先通过父类的构造函数完成塑造得到与父类同样的实例属性和方法然后再对其进行加工添加子类自己的实例属性和方法。如果不调用super()方法子类就得不到自己的this对象。
二、super关键字
super关键字用于调用父类的方法。在子类的方法中可以使用super关键字来调用父类的方法。使用super关键字时需要指定要调用的父类方法语法如下
super(); // 调用父类的构造函数
super.父类方法(); // 调用父类的方法
super.属性; // 访问父类的属性例如在上面的例子中在Student类的构造函数中使用了super关键字来调用父类的构造函数
constructor(name, age, grade) {super(name, age); // 调用父类的构造函数this.grade grade;
}另外在子类的方法中也可以使用super关键字来调用父类的方法。例如
class Person {constructor(name) {this.name name;}sayHello() {console.log(Hello, my name is ${this.name});}
}class Student extends Person {constructor(name, grade) {super(name); // 调用父类的构造函数this.grade grade;}sayHello() {super.sayHello(); // 调用父类的方法console.log(Im a student in grade ${this.grade});}
}在上面的例子中Student类继承了Person类并重写了sayHello方法。在重写的sayHello方法中使用super关键字来调用父类的sayHello方法。