ES6之前的继承方法
基本思想:
1.1在子类的构造函数中通过call/apply借助父类的构造函数
1.2将子类的原型对象修改为父类的实例对象(即通过prototype和构造函数实现)
function Person(myName, myAge) {
this.name = myName;
this.age = myAge
}
Person.prototype.say = function () {
console.log(this.name, this.age);
}
function Student(myName, myAge, myScore) {
//1.在子类中通过call/apply方法借助父类的构造函数
Person.call(this, myName, myAge);
this.score = myScore;
this.study = function () {
console.log("day day up");
}
}
//2.将子类的原型对象设置为父类的实例对象
Student.prototype = new Person();
Student.prototype.constructor = Student;
let stu = new Student("zs", 18, 99)
console.log(stu);
ES6继承
基本思想:
通过extend关键字实现继承,子类可以继承父类中所有的方法和属性,子类必须在construc()方法中调用super()方法,因为新建的子类没有自己的this对象,而是继承了父类的this对象;
实质:利用extend关键字继承父类,然后继承父类的属性和方法
使用:
- 解决代码的复用
- 使用extends关键字实现继承
- 子类可以继承父类中所有的方法和属性
- 子类只能继承一个父类(单继承),一个父类可以有多个子类
- 子类的构造方法中必须有super()来指定调用父类的构造方法,并且位于子类构造方法中的第一行
- 子类中如果有与父类相同的方法和属性,将会优先使用子类的(覆盖)
class Person{
constructor(myName, myAge){
//this = stu
this.name = myName; //stu.name = myName
this.age = myAge; //stu.age = Age
}
say(){
console.log(this.name, this.age);
}
}
//以下代码的含义:student这个类需要继承person这个类
class Student extends Person{
constructor(myName, myAge, myScore){
//1.在子类中通过call/apply借助父类的构造函数
//Person.call(this, myName, myAge)
super(myName, myAge);
this.score = myScore
}
}