我们都知道JS有6种继承方式,今天我们具体讲讲JS 6种继承方式分别是哪些
第一种原型链继承
/* 1原型链继承
通过在原型链上拓展属性进行继承
缺点:
1 新实例无法向父类传参.
2所有的新实例会继承父类的所有属性.
3 继承单一
4 新实例不会继承父类实例的属性!
*/
function Child(name) {
this.name=name
}
function Father() {
}
Father.prototype.getName=function () {
console.log(this.name)
}
Child.prototype=new Father()
let child=new Child('ligo')
child.getName() //ligo
第二种构造继承
/*
* 第二种构造继承
* 解决问题:1 可传参 解决原型链继承的缺点
* 缺点:1 只能读取父类构造函数的属性 2无法实现构造函数的复用
* */
function Child(name, age) {
this.name=name
this.age=age
Father.apply(this, arguments)
}
function Father(name,age) {
this.getInfo = function () {
console.log(name, age)
}
}
let child = new Child('ligo', 18)
child.getInfo()
第三种组合继承
* 3 组合继承
* 优点:1 结合两种模式的优点 可传参可复用 可读取父类原型的属性
* 缺点:调用了两次父类构造函数 消耗内存
* */
function Child(age, name) {
this.name = name
this.age = age
Father.apply(this, arguments)
}
function Father(name,age) {
}
Father.prototype.work='study'
Father.prototype.getName = function () {
console.log(this.name, this.age)
}
Child.prototype = new Father()
Child.prototype.constructor = Child
let child = new Child('ligo', 18)
child.getName()
console.log(child.work) //work
第四种原型式继承
/*
* 4 原型式继承
* 缺点:1 所有实例都会继承原型上的属性。2 无法实现复用。
* */
function createObj(o) {
function F() {
}
F.prototype = o
return new F()
}
let obj={
name:'ligo',
age:18
}
let obj2=createObj(obj)
console.log(obj2.name)
console.log(obj2.age)
第五种寄生式继承
/*
* 寄生式继承
* 缺点:没有用到原型无法复用
* */
function createObj(o) {
function F() {
}
F.prototype=o
return new F()
}
function cloneObj(obj) {
let clone = createObj(obj)
clone.getInfo = function () {
console.log(this.name)
}
return clone
}
let obj={
name:'ligo',
age:18
}
let obj2=cloneObj(obj)
obj2.getInfo()
第六种寄生组合式继承
/*
* 寄生组合式继承 常用
* 优点:修复了组合继承的问题(多次调用)
* */
function Child(name,age) {
this.name=name
this.age=age
Father.apply(this,arguments)
}
function Father(name,age) {
}
Father.prototype.getInfo=function () {
console.log(this.name,this.age)
}
function createObj(o) {
function F() {
}
F.prototype=o
return new F()
}
function protoType(child,parent) {
let protoType=createObj(parent.prototype) //new Father
protoType.constructor=child
child.prototype=protoType
}
protoType(Child,Father)
let obj=new Child('ligo',18)
obj.getInfo()
console.log(obj)