js 继承的方式

25 阅读1分钟
function Man(name){
	this.name = name
}
Man.prototype.someThing = function(){}

1.原型链继承
缺点:1.子类实例化,无法向父类传参2.共用一个原型对象

function Parent(){}
Parent.prototype = new Man("1")
const p1 = new Parent()
const p2 = new Parent()

2.经典继承(构造函数继承)
缺点:1.原型链断裂2.子类无法继承父类中的原型方法

function Parent(name){
	Man.call(this,name)
}
const p1 = new Parent("11")
const p2 = new Parent("12")
p1.__proto__ === Parent.prototype  //true
Parent.__proto__ === Man.prototype//false
p1.__proto__.__proto__ === Man.prototype //false

3.组合继承
父类调用两次,浪费内存

function Parent(name){
	Man.call(this,name)
}
Parent.prototype = new Man()
const p1 = new Parent("11")
const p2 = new Parent("12")

4.寄生组合继承

function Parent(name){
	Man.call(this.name)
}
Parent.prototype = Object.create(Man.prototype)
Parent.prototype.constructor = Parent
const p1 = new Parent("11")
const p2 = new Parent("12")