本文主要介绍六种实现继承的方式及其各自的优缺点,依次为原型链继承、构造函数继承、组合继承、原型继承、寄生继承、寄生组合继承1.原型链继承的优点:父类的方法类可以重用。:1)引用类型会被子类改变;2)不能传递参数//代码1functionFa(){this.name='fa'this.info={age:11}}Fa.prototype.sayName=function(){console.log(this.name);}functionSon(){}Son.prototype=newFa();//核心Son.prototype.constructor=Son;//添加2、构造函数继承优点:1)是传参;2)不会共享引用属性;缺点:子类无法访问父类上的原型;functionFa(){this.name='fa'this.info={age:11}}Fa.prototype.sayName=function(){console.log(this.name);}functionSon(){Fa.call(this)//core}3.组合继承的优点:结合了以上两个优点functionFa(){this.name='fa'this.info={age:11}}Fa.prototype.sayName=function(){console.log(this.name);}functionSon(){Fa.call(this)}Son.prototype=newFa();Son.prototype.constructor=Son;4.原型继承的优点:父类的方法可以复用缺点:1)引用类型会被子类改变;2)子类声明不能传参;让Fa={name:'Fa',groups:[1,2,3],sayName:function(){console.log(this.name);}}letson=Object.create(FA);//核心5,寄生继承是在4)的基础上,增加了子类特有的方法,优缺点同上;让Fa={name:'Fa',groups:[1,2,3],sayName:function(){console.log(this.name);}}functionmyCreate(obj){letclone=Object.create(obj);//自定义新方法clone.getName=function(){console.log(this.name+'haha');}returnclone;}6.寄生组合继承综合了以上所有优点,是class的内部实现//核心函数functioninheritPrototype(child,parent){letprototype=Object.create(parent.prototype);//创建对象prototype.constructor=child;//增强对象Child.prototype=prototype;//赋值对象}//定义父类functionParent(name){this.name=name;this.friends=["rose","lily","tom"]}Parent.prototype.sayName=function(){console.log(this.name);}functionChild(name,age){Parent.call(这个,名字);这。年龄=年龄;}inheritPrototype(孩子,父母);
