1. 原型链继承
- 核心
- 优点
- 缺点
- 多子类实例,父类型
属性会共享
- 子类实例
无法传递参数
function Parent() { this.color = ['red'] }
function Child() {}
Child.prototype = new Parent()
const child1 = new Child()
const child2 = new Child()
child1.color.push('blue')
console.log(child1.color)
console.log(child2.color)
2. 构造函数
- 核心
- 优点
- 缺点
只能继承构造函数中的属性和方法,无法继承原型上的属性和方法
function Parent(name) {
this.name = name
this.color = ['red']
}
Parent.prototype.age = 12
Parent.prototype.sayName = function () {
console.log(this.name)
}
function Child(name) {
Parent.call(this, name)
}
const child1 = new Child('hh')
const child2 = new Child('xx')
child1.color.push('blue')
console.log(child1.name, child1.color)
console.log(child2.name, child2.color)
console.log(child1.sayName)
console.log(child1.age)
3. 组合继承
- 核心
- 优点
- 父类
构造函数和原型上的方法和属性都可以继承
- 子类实例
属性和方法独立,不相互影响
- 缺点
- 父类构造函数会
调用两次,一次在子类构造函数中,一次在子类原型赋值时
function Parent(name) {
this.name = name
this.color = ['red']
}
Parent.prototype.age = 12
Parent.prototype.sayName = function () {
console.log(this.name)
}
function Child(name) {
Parent.call(this, name)
}
Child.prototype = new Parent()
Child.prototype.constructor = Child
const child1 = new Child('hh')
const child2 = new Child('xx')
child1.color.push('blue')
console.log(child1.name, child1.color)
console.log(child2.name, child2.color)
console.log(child1.sayName())
console.log(child1.age)
4. 寄生组合继承(最优解)
- 优点
避免父类构造函数调用两次
- 父类
构造函数和原型上的方法和属性都可以继承
- 子类实例
属性和方法独立,不相互影响
function Parent(name) {
this.name = name
this.color = ['red']
}
Parent.prototype.age = 12
Parent.prototype.sayName = function () {
console.log(this.name)
}
function Child(name) {
Parent.call(this, name)
}
function inheritPrototype(child, parent) {
const newConstructor = Object.create(parent.prototype)
child.prototype = newConstructor
child.prototype.constructor = child
}
inheritPrototype(Child, Parent)
const child1 = new Child('hh')
const child2 = new Child('xx')
child1.color.push('blue')
console.log(child1.name, child1.color)
console.log(child2.name, child2.color)
console.log(child1.sayName())
console.log(child1.age)
5. ES6 Class继承 (优先使用)
- 核心
- es6中的
class 和 extends 关键词
- 优点
- 缺点
- 有一定
兼容性问题,在不支持ES6语法的环境中需要转换
class Parent {
age = 12
constructor (name) {
this.name = name
this.color = ['red']
}
sayName() {
console.log(this.name)
}
}
class Child extends Parent {
constructor(name) {
super(name)
}
}
const child1 = new Child('hh')
const child2 = new Child('xx')
child1.color.push('blue')
console.log(child1.name, child1.color)
console.log(child2.name, child2.color)
console.log(child1.sayName())
console.log(child1.age)