原型链继承
function Parent(){}
const parent = new Parent()
Child.prototype = parent
function Child(){}
Child.prototype.name = 'sun'
const child = new Child()
console.log(child)
console.log(parent)
特点
1、来自原型对象的所有属性被所有实例共享,即,改变 Child.prototype.name,Parent.prototype.name 同时被改变了,不满足隔离性。
2、创建子类实例时,无法向父类构造函数传参。
构造函数继承
function Parent(){}
function Child(){
Parent.call(this)
}
Child.prototype.name = 'sun'
const parent = new Parent()
const child = new Child()
console.log(child)
console.log(parent)
特点
1、解决了原型链继承方式的子类共享父类原型对象的问题。
2、解决了原型链继承方式无法向父类构造函数传参问题。
3、不能继承父类原型属性
寄生组合继承 / 圣杯模式
function Parent(){}
function Child(){}
function Buffer(){}
Buffer.prototype = Parent.prototype
const buffer = new Buffer()
Child.prototype = buffer
Child.prototype.name = 'sun'
const parent = new Parent()
const child = new Child()
console.log(child)
console.log(parent)
特点
1、堪称完美,但较为复杂。
类的继承
class Parent {}
class Child extends Parent {}