前言
在学习VUE的过程中,发现VUE和VueCompents是继承关系,自省发现自己连寄生组合式继承都忘完了,就记录一下自己的复习收获
继承的方式
原型链继承
function Father(name){
this.name = name
this.colors = ["red", "blue"]
this.level ="父级"
}
function Son(){
this.level="子级"
}
Son.prototype = new Father()
let s1 = new Son()
s1.colors.push("yellow")
let s2 = new Son()
console.log(s1.colors) //["red", "blue", "yellow"]
console.log(s2.colors) //["red", "blue", "yellow"]
-
缺点
- 如果原型中属性是引用类型
(Array、OBject),在某个实例对象中修改该引用对象属性的值中会影响到原型中的值,也就会影响其他实例对象中该属性的值;===》(当s1改变colors数组的值时,s2访问的colors值也发生了改变)
- 在创建实例对象的时候,不能向继承对象传递初始参数;===》(在创建s1、s2时,无法给原型传递参数)
- 如果原型中属性是引用类型
借用构造函数继承
function Father(name){
this.name = name
this.level ="父级"
}
Father.prototype.say = function(){
console.log(this.name)
}
function Son(name){
Father.call(this,name)
this.level="子级"
}
let s1 = new Son("李白")
console.log(s1.name) //李白
-
缺点
- 不能访问继承对象原型链上面的方法;===》(s1无法访问
Father.prototype上的say方法)
- 不能访问继承对象原型链上面的方法;===》(s1无法访问
组合继承
function Father(name){
this.name = name
this.level ="父级"
}
function Son(name){
Father.call(this,name)
this.level="子级"
}
Son.prototype = new Father()
let s1 = new Son("李白")
-
缺点
- 会执行两次继承构造函数;===》(在执行
Father.call(this,name)和new Father()都会执行Father方法,并且Father方法的数据也会同时出现在原型和对象上面)
- 会执行两次继承构造函数;===》(在执行
寄生继承
function Father(name){
this.name = name
this.level ="父级"
}
function Son(){
this.level="子级"
}
let Fn = function(){}
Fn.prototype = new Father()
let son = new Fn()
son.toSay = function(){
console.log("toSay")
}
Son.prototype = son
-
缺点
- 无法继承非原型上面的属性和方法;===》(无法访问
Father的level熟悉值)
- 无法继承非原型上面的属性和方法;===》(无法访问
寄生组合式继承(最优方式)
function Father(name){
this.name = name
this.level ="父级"
}
function Son(){
Father.call(this,name)
this.level="子级"
}
let Fn = function(){}
Fn.prototype = new Father()
let son = new Fn()
son.toSay = function(){
console.log("toSay")
}
Son.prototype = son
\