基于原型继承
原型实现继承的核心在于通过子类的构造函数中通过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()