2、类的继承
1.继承
现实中的继承:子承父业,比如我们都继承了父亲的姓。
程序中的继承:子类可以继承父类的一些属性和方法。
语法:
class Father{ // 父类
}
class Son extends Father { // 子类继承父类
}
实例:
class Father {
constructor(surname) {
this.surname= surname;
}
say() {
console.log('你的姓是' + this.surname);
}
}
class Son extends Father{ // 这样子类就继承了父类的属性和方法
}
var damao= new Son('刘');
damao.say();
以上代码运行结果:
2.super 关键字
super 关键字用于访问和调用对象父类上的函数。可以调用父类的构造函数,也可以调用父类的普通函数
语法:
class Person { // 父类
constructor(surname){
this.surname = surname;
}
}
class Student extends Person { // 子类继承父类
constructor(surname,firstname){
super(surname); // 调用父类的constructor(surname)
this.firstname = firstname; // 定义子类独有的属性
}
}
实例一(调用父类中的构造函数):
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x, y) {
super(x, y);
//调用了父类中的构造函数
}
}
var son = new Son(1, 2);
var son1 = new Son(11, 22);
son.sum(); // 3
son1.sum(); // 33
实例二(调用父类中的普通函数):
class Father {
say() {
return '我是爸爸';
}
}
class Son extends Father {
say() {
// console.log('我是儿子');
console.log(super.say() + '的儿子');
// super.say() 就是调用父类中的普通函数 say()
}
}
var son = new Son();
son.say();
实例三(子类继承父类方法同时扩展自己方法):
// 父类有加法方法
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
// 子类继承父类加法方法 同时 扩展减法方法
class Son extends Father {
constructor(x, y) {
// 利用super 调用父类的构造函数
// super 必须在子类this之前调用
super(x, y);
this.x = x;
this.y = y;
}
subtract() {
console.log(this.x - this.y);
}
}
var son = new Son(5, 3);
son.subtract(); // 输出2
son.sum(); // 输出8
- 继承中的属性或者方法查找原则: 就近原则
- 继承中,如果实例化子类输出一个方法,先看子类有没有这个方法,如果有就先执行子类的,如果子类里面没有,就去查找父类有没有这个方法,如果有,就执行父类的这个方法
3.this指向问题
-
类里面的共有的属性和方法一定要加this使用
-
constructor中的this指向的是new出来的实例对象
-
自定义的方法,一般也指向的new出来的实例对象
-
绑定事件之后this指向的就是触发事件的事件源
个方法
3.this指向问题
-
类里面的共有的属性和方法一定要加this使用
-
constructor中的this指向的是new出来的实例对象
-
自定义的方法,一般也指向的new出来的实例对象
-
绑定事件之后this指向的就是触发事件的事件源