继承
写在前面,熟悉了vue API以后,再回过头来学习js,不要急,按自己的节奏慢慢来,基础打的牢,楼房才建的高。
类似继承
//类似继承
//声明父类
function Super(){
this.value=true
}
//为父类添加共有方法
Super.prototype.getValue=function(){
return this.value
}
//声明子类
function Sub(){
this.subValue=false
}
//继承父类
Sub.prototype=new Super()
//为子类添加共有方法
Sub.prototype.getSubValue=function (){
return this.subValue
}
缺点:
- 1 子类通过原型prototype对父类进行实例化,继承了父类,如果父类中的属性是引用类型,就会在子类重被所有实例所共用,因此其中某一个子类的更改了子类原型从父类构造函数中继承来的共有属性就会影响到其他子类;
- 2 创建父类的时候,不能向父类传递参数,实例化父类的时候也无法对父类的构造函数内的属性进行初始化。
构造函数继承
function Super(id){
this.books=['javascript','html','css']
this.id=id
}
Super.prototype.showBooks=function(){
console.log(this.books)
}
function Sub(){
Super.call(this,id)
}
let instance=new Sub(22)
组合继承
function Super(name){
this.name=name
thiss.books=["javaScript","html","css"]
}
Super.prototype.getName=function (){
console.log(this.name)
}
function Sub(name,time){
Super.call(this,name)
this.time=time
}
Sub.prototype=new Super()
Sub.prototype.getTime=function(){
console.log(this.time)
原型式继承
funtion inheritObject(o){
function F(){}
F.prototype=o
return new F()
}
子类改变继承父类的属性,其他子类也会改变。
寄生式继承
let book={
name:"gege",
books:["javaScript","html","css"]
}
funtion inheritObject(o){
function F(){}
F.prototype=o
return new F()
}
function createBook(obj){
let o=new inheritObject(obj)
o.getName=function(){
console.log(name)
}
return o
}
寄生组合式继承
function inheritPrototype(sub,super){
let p=inheritObject(super.prototype)
//修正构造器
p.constructor=sub
sub.prototype=p
}
function Super(name){
this.name=name;
this.books=["javaScript","html","css"]
}
Super.prototype.getName=function(){
console.log(name)
}
function Sub(name,time){
Sub.call(this,name)
this.time=time}
inheritPrototype(Sub,Super)
Sub.prototype.getTime=function(){
console.log(this.time)
}
多继承
//只能复制值类型的属性,不能复制引用类型
let extend=function(target,source){
for(let property in source){
target[property]=source[property]
}
return target
}
let mix=function(){
let len=arguments.length
let target=arguments[0]
let arg
//遍历被继承的对象
for(let i=1; i<len;i++){
//缓存当前对象
arg=arguments[i]
//便利被继承对象中的属性
for(let property in arg){
target[property]=arg[property]
}
}
return target
}