一.es5
构造函数相当于类
父类的属性通过构造函数this对象进行初始化,父类的方法通过在prototype原型对象上挂载,供所有的实例对象使用,减少内存浪费。
子类继承父类的属性通过call方法借调父类的构造函数进行父类属性继承,子类特有的属性同样通过this来初始化,子类继承父类的方法通过...展开运算符对父类prototype原型对象进行浅拷贝,子类特有的方法同样通过子类的prototype原型对象上挂载方法,供所有实例对象使用。
案例:
//父类
function Father(name, age) {
// 父类的属性
this.name = name
this.age = age
}
//父类的方法
Father.prototype.say = function () {
console.log(this.name + '会说话');
}
// 子类
function Son(name, age, school) {
//继承父类的属性
Father.call(this, name, age)
//子类自己的属性
this.school = school
}
//子类继承父类的方法
Son.prototype = { ...Father.prototype }//浅拷贝
Son.prototype.constructor = Son
//子类自己的方法
Son.prototype.toSchool = function () {
console.log(`${this.name}去${this.school}学校`);
}
const son = new Son('h', 21, 'gxkj')
//父类方法
son.say()
// 自己的方法
son.toSchool()
二、es6
通过class关键字声明类
父类的属性初始化在constructor构造器中进行初始化,方法直接书写在类中
子类的属性在constructor构造器中进行初始化,继承父类的属性通过在子类的constructor构造器中
通过super函数调用父类的构造器,自己特有的属性通过this进行初始化,子类自动会继承父类的方法,自己特有的方法直接书写在子类中
//父类
class Father {
//父类构造器中进行实例对象属性的初始化
constructor(name, age) {
// 父类的属性
this.name = name
this.age = age
}
//父类的方法
say() {
console.log(this.name + '会说话');
}
}
// 子类
class Son extends Father {
//子类构造器中进行实例对象属性的初始化
constructor(name, age, school) {
// 继承父类的属性
super(name, age)
// 子类自己的属性
this.school = school
}
//父类方法自动继承
//子类自己的方法
toSchool() {
console.log(`${this.name}去${this.school}学校`);
}
}
//测试
const son = new Son('h', 21, 'gxkj')
//父类方法
son.say()
// 自己的方法
son.toSchool()