//JS的继承
//1.继承:将父类的 “特点”传给 子类,例如 方法,属性
/*
1.1类式继承
弊端:1.不能让父类的引用类型的资源分别赋值给子类,
导致所有子类共享父类同一资源,谁修改了都会影响全局
2.不能不能复用父类代码
3.构造父类时 父类函数调用了两次
*/
function Father(name,age){
this.name=name;
this.age=age;
this.book=["JavaScript","HTML"]
}
let Son=(function (){
function _son(name,age){
this.name=name;
this.age=age;
}
//绑定父类对象
let f=new Father();
_son.prototype=new Father();
return _son;
}());
let instance1=new Son("张三",100);
let instance2=new Son("李四",77);
instance1.book.push("设计模式");
console.log(instance1.book);
console.log(instance2.book);
/*
1.2构造函数式继承
好处:解决了类式继承中父类资源被共享的问题;复用了父类代码
弊端:1.父类构造函数被执行了两次,性能依旧受影响
2.不能共享父类公有方法【没有修改子类原型】
*/
function Father(name,age){
this.name=name;
this.age=age;
this.book=['JavaScript','HTML']
}
let Son=(function (){
function _son(name,age){
Father.call(this,name,age);//重点
this.other="other";
}
return _son;
}())
let instance1=new Son("张三",100);
instance1.book.push("设计模式")
let instance2=new Son("李四",1000);
console.log(instance1.book);
console.log(instance2.book);
/*
1.3:组合继承:类式继承和构造函数继承组合
好处:在类继承的基础上解决了共享父类共有方法
弊端:1.父类构造函数执行了两次,性能降低
*/
function Father(name,age){
this.name=name;
this.age=age;
this.book=['JavaScript','HTML']
}
let Son=(function (){
function _son(name,age){
Father.call(this,name,age);//重点
this.other="other";
}
_son.prototype=new Father();
return _son;
}())
let instance1=new Son("张三",100);
instance1.book.push("设计模式")
let instance2=new Son("李四",1000);
console.log(instance1.book);
console.log(instance2.book);
console.log(Son instanceof Father)
/*
1.4终极继承:组合寄生继承
*/
function extend(sonClass,fatherClass){
function F(){}
F.prototype=fatherClass.prototype;
const p=new F();
p.constructor=sonClass;
sonClass.prototype=p;
}
extend(SonClass,FatherClass)
function FatherClass(name,age){
this.name=name;
this.age=age;
this.book=['HTML','JavaScript']
}
function SonClass(name,age,hobby){
FatherClass.call(this,name,age);
this.hobby=hobby
}
//测试
let instance1=new SonClass('小明',18,"左手拿筷子");
let instance2=new SonClass('小光',20,"右手拿筷子");
instance1.book.push('设计模式')
console.log(instance1);
console.log(instance2);
console.log(instance1 instanceof SonClass)//true
console.log(instance2 instanceof FatherClass)//true