一、组合继承(最常用的继承)
这种继承方式组合了原型链和借用构造函数的方式,实现了一个最为常用继承的方式。
主要有几个很关键的步骤:
- 在子类构造函数调用父类构造函数,使用
call
或apply
来指定父类中的this
为子类。这一步相当于子类继承了父类构造函数中属性及方法,传入参数即可。注意的是原型中的属性和方法还是访问不到的。
Person.call(this, name, age);
- 将子类的原型对象绑定在父类实例对象上,从而形成原型链访问到父类原型对象,并将原型对象中的
constructor
指向构造函数。
Student.prototype = new Person();
Student.prototype.constructor = Student;
我这有一个Person
类和Student
类,而Student
继承自Person
类:
'use strict';
// Person类
function Person(name, age) {
this.name = name;
this.age = age;
}
// Person类的方法
Person.prototype.sayHi = function () {
console.log(`hello,this is ${
this.name}`);
};
// Student类
function Student (name, age, grade) {
// 调用Person构造函数,传入参数,从而当前对象的this就有了父类的属性
Person.call(this, name, age);
this.grade = grade
}
// 实现继承,指定原型和构造器
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.study = function () {
console.log(`I love study,my grade is ${
this.grade