网站改版设计费进什么科目磁力蜘蛛搜索引擎
在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(`I'm 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(`I'm a student in grade ${this.grade}`);}
}
在上面的例子中,Student类继承了Person类,并重写了sayHello方法。在重写的sayHello方法中,使用super关键字来调用父类的sayHello方法。