一 原型链继承
1.通过原型类型继承多个引用类型的属性和方法
function Super(){
this.pro=true
}
Super.prototype.getsuper=function(){
return this.pro
}
function sub(){
this.subpro=false
}
//继承super
sub.prototype=new Super()
sub.prototype.getsub=function(){
return this.subpro
}
let ins=new sub()
console.log(sub.prototype.__proto__===Super.prototype);//true
console.log(ins.getsuper());//true
console.log(ins.getsub());//false
//原型链扩展了原型搜索机制,读取实例上属性时,先会在实例上寻找,如过没找到,则会继承搜索实例的原型
//在通过原型链实现继承之后,搜索就可以继承向上,搜索原型的原型
//调用ins.getsuper()经历了3步,ins、sub.prototypr、Super.prototype
2.默认原型
默认情况下,所有引用类型都继承自就object
二 盗用构造函数
1.为了解决原型包含的引用值导致的继承问题
2.在子类构造函数中调用父类构造函数,因为函数就是在特定上下文执行的简单对象
function Super(){
this.colors=['red','blue']
}
function sub(){
//继承Super
Super.call(this)
}
let ins = new sub
ins.colors.push('black')
console.log(ins.colors);//[ 'red', 'blue', 'black' ]
let ins1=new sub
console.log(ins1.colors);//[ 'red', 'blue' ]
3.传递参数
//子类构造函数像父类构造函数传参
function Super(name){
this.name=name
}
function sub(){
Super.call(this,'hello')
this.age=20
}
let ins=new sub
console.log(ins.age);
console.log(ins.name);
//20
//hello
三 组合继承
function Super(name){
this.name=name
this.colors=['red','blue']
}
Super.prototype.sayName=function(){
console.log(this.name);
}
function sub(name,age){
//继承属性
Super.call(this,name)
this.age=age
}
//继承方法
sub.prototype=new Super
sub.prototype.sayAge=function(){
console.log(this.age);
}
let ins=new sub('hello',20)
ins.colors.push('black')
console.log(ins.colors);//[ 'red', 'blue', 'black' ]
console.log(ins.sayAge());//20
console.log(ins.sayName());//hello
let ins1=new sub('hello1',21)
console.log(ins1.colors);//[ 'red', 'blue' ]
console.log(ins1.sayAge());//21
console.log(ins1.sayName());//hello1