基于原型繼承
原型實(shí)現(xiàn)繼承的核心在于通過(guò)子類(lèi)的構(gòu)造函數(shù)中通過(guò)Parent.call(this)
繼承父類(lèi)的屬性蔗候,然后改變子類(lèi)的原型為new Parent()
來(lái)繼承父類(lèi)的函數(shù)族檬。
//ES5原型鏈構(gòu)造對(duì)象
//父類(lèi)
function People(name, age) {
this.name = name || 'pray'
this.age = age || 27
}
//父類(lèi)方法
People.prototype.sayHi = function () {
console.log(this.name + ' of ' + this.age + ' sayHi')
}
//ES5原型鏈繼承對(duì)象
//子類(lèi)
function Student(name, age) {
//繼承父類(lèi)屬性
People.call(this, name, age)
}
//繼承父類(lèi)方法
(function () {
// 創(chuàng)建空類(lèi)
let Super = function () { };
Super.prototype = People.prototype;
//父類(lèi)的實(shí)例作為子類(lèi)的原型
Student.prototype = new Super();
})();
//修復(fù)構(gòu)造函數(shù)指向問(wèn)題
Student.prototype.constructor = Student;
let studentObj = new Student();
studentObj.sayHi()
基于Class繼承
class實(shí)現(xiàn)繼承的核心在于使用extends
表明繼承自哪個(gè)父類(lèi),并且在子類(lèi)構(gòu)造函數(shù)中必須調(diào)用super
繼承父類(lèi)屬性和方法惭嚣。
// ES6 Class構(gòu)造對(duì)象
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 繼承父類(lèi)
class Student extends People {
constructor(name = 'student1', age = '22', score = 90) {
//繼承父類(lèi)屬性
super(name, age);
//自身屬性
this.score = score;
}
sayHi() {
//繼承父類(lèi)屬性方法
super.sayHi()
//自身方法
console.log('score:' + this.score)
}
}
let person = new Student()
person.sayHi()