# 3.类的继承
# 3.1 继承
现实中的继承:子承父业,比如继承父亲的姓
程序中的继承:子类可以继承父类的一些属性和方法
// 父类
class Father{
constructor(){
}
// 方法
money(){
console.log('小钱钱');
}
}
// 子类——继承于父类
// 通过 extends 关键字 实现继承
class Son extends Father{
}
// 实例
var son = new Son()
// 因为 Son 类 继承于 Father 类,所以Son类也拥有Father类中的money()方法
son.money();
# 3.2 super关键字
class Person{
constructor(name){
this.name = name;
}
sayHello(){
console.log('I am' + this.name);
}
}
class Student extends Person{
constructor(name){
this.name = name;
}
}
var student = new Student('张三');
student.sayHello();
上述代码能够执行么?
并不能,因为父类构造函数中的this,是指向父类的实例,而子类构造函数中的this,是指向子类的实例,二者没有实现继承。
要想继承父类的属性,需要在子类中调用父类的构造函数,就需要使用super关键字
super关键字用于访问和调用对象父类上的函数。可以调用父类的构造函数,也可以调用父类的普通函数
# super关键字 调用父类构造函数
所以,正确的属性继承,应该这样。
class Person{
constructor(name){
this.name = name;
}
sayHello(){
console.log('I am ' + this.name);
}
}
class Student extends Person{
constructor(name){
super(name); // 调用了父类的构造函数
}
}
var student1 = new Student('张三');
student1.sayHello();
var student2 = new Student('李四');
student2.sayHello();
# super关键字调用父类普通函数
class Person{
say(){
return '我是个人';
}
}
class Student extends Person{
say(){
console.log('我是学生');
}
}
var student = new Student();
student.say(); // 这里调用的是哪个say()方法?
// 继承中,如果实例化子类输出一个方法,先查看子类中是否有这个方法(就近原则)
class Teacher extends Person{
say(){
// 调用父类普通函数
console.log(super.say() + '然后再是老师');
}
}
var teacher = new Teacher();
teacher.say();
# 继承父类的方法并扩展
class Person{
constructor(name){
this.name = name;
}
say(){
console.log('I am' + this.name);
}
}
class Student extends Person{
constructor(name,subject){
super(name);
this.subject = subject;
}
study(){
console.log(this.name + '正在学习' + this.subject);
}
}
var student = new Student('张三', '犯罪心理学');
student.say();
student.study();