基于原型继承
原型实现继承的核心在于通过子类的构造函数中通过Parent.call(this)继承父类的属性,然后改变子类的原型为new Parent() 来继承父类的函数。
//ES5原型链构造对象//父类function People(name, age) {this.name = name || 'pray'this.age = age || 27}//父类方法People.prototype.sayHi = function () {console.log(this.name + ' of ' + this.age + ' sayHi')}//ES5原型链继承对象//子类function Student(name, age) {//继承父类属性People.call(this, name, age)}//继承父类方法(function () {// 创建空类let Super = function () { };Super.prototype = People.prototype;//父类的实例作为子类的原型Student.prototype = new Super();})();//修复构造函数指向问题Student.prototype.constructor = Student;let studentObj = new Student();studentObj.sayHi()
基于Class继承
class实现继承的核心在于使用extends表明继承自哪个父类,并且在子类构造函数中必须调用super继承父类属性和方法
// ES6 Class构造对象class People {constructor(name = 'pray', age = 18) {this.name = name;this.age = age;}sayHi() {console.log(this.name + ' of ' + this.age + ' says Hi!')}}//ES6 extends 继承父类class Student extends People {constructor(name = 'student1', age = '22', score = 90) {//继承父类属性super(name, age);//自身属性this.score = score;}sayHi() {//继承父类属性方法super.sayHi()//自身方法console.log('score:' + this.score)}}let person = new Student()person.sayHi()
