一、原型链继承
- 套路:
- 定义父类型的构造函数
- 给父类型的原型添加方法
- 定义子类型的构造函数
- 创建父类型的对象赋值给子类型的原型
- 将子类型原型的构造属性设置为子类型
- 给子类型原型添加方法
- 创建子类型的对象:可以调用父类型的方法
- 关键:
子类型的原型为父类型的一个实例对象
// 父类型
function Super() {
this.superText = 'aaa';
}
Super.prototype.showSuperText = function() {
console.log(this.superText);
}
// 子类型
function Sub() {
this.superText = 'bbb';
}
// 子类型的原型为父类型的一个实例对象
Sub.prototype = new Super();
// 让子类型的原型的constructor指向子类型
Sub.prototype.constructor = Sub;
Sub.prototype.showSubText = function() {
console.log(this.subText);
}
二、借用构造函数继承
- 套路:
- 定义父类型的构造函数
- 定义子类型的构造函数
- 在子类型构造函数中调用父类型的构造函数
- 关键:
在子类型构造函数中通过call()调用父类型构造函数
function Person(name, age) {
this.name = name;
this.age = age;
}
function Animal(name, age, sex) {
Person.call(this, name, age);
this.sex = sex;
}
三、原型链+借用构造函数的组合继承
- 利用原型链实现对父类型对象的方法继承
- 利用call()借用父类型构造函数初始化相同属性
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.setName = function(name) {
this.name = name;
}
function Animal(name, age, sex) {
Person.call(this, name, age);
this.sex = sex;
}
Animal.prototype = new Person();
Animal.prototype.constructor = Animal;
Animal.prototype.setSex = function(sex) {
this.sex = sex;
}
四、ES6类继承
在ES6中引入了类的概念,通过class关键字和extends关键字可以实现类的继承。
class Parent {
constructor(name) {
this.name = name;
}
sayHello() {
console.log('Hello');
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 必须要有super()
this.age = age;
}
}
const child = new Child('Child');
console.log(child.name); // Child
child.sayHello(); // Hello