1.类式继承
缺点:1.如果父类中有引用类型的字段,会被子类的各个实例共享,一个改动则会影响别的实例
2.不能借用父类构造器产生子类需要的字段
//声明父类
function Super(){
this.book=['js','html']
}
//声明子类
function Sub(){
}
//继承
Sub.prototype=new Super()
//实例化
let instance1=new Sub()
let instance2=new Sub()
instance1.book.push("C++")
console.log(instance1);
console.log(instance2);
2.构造函数式继承
缺点:不能使用父类原型链上的共有方法
//声明父类
function Super(){
this.book=['js','html']
}
//声明子类
function Sub(){
//继承
Super.call(this)
this.other="other"
}
//实例化
let instance1=new Sub()
let instance2=new Sub()
instance1.book.push("C++")
console.log(instance1);
console.log(instance2);
3.组合继承
//声明父类
function Super(){
this.book=['js','html']
}
//声明子类
function Sub(){
Super.call(this)
this.other="other"
}
Sub.prototype=new Super()
//实例化
let instance1=new Sub()
let instance2=new Sub()
instance1.book.push("C++")
console.log(instance1);
console.log(instance2);
4.寄生组合式继承
//声明父类
function Super(){
this.book=['js','html']
}
//声明子类
function Sub(){
Super.call(this)
this.other="other"
}
//继承函数
function extend(subClass,superClass){
function F(){}
F.prototype=superClass.prototype
let p=new F()
subClass.prototype=p
p.constructor=subClass
}
//继承
extend(Sub,Super)
//实例化
let instance1=new Sub()
let instance2=new Sub()
instance1.book.push("C++")
console.log(instance1);
console.log(instance2);