PrototypePrototype是Javascript中继承的基础,Javascript中的继承是对原型的继承。构造函数其实就是我们平时写的函数,我们可以使用new关键字来创建一个实例,我们称之为构造函数。当声明一个函数时,浏览器会自动生成一个原型对象并存储在内存中。functionadd(){leta=1}constf=newadd()//add()是一个构造函数//f是构造函数的实例原型链add()_proto_链接起来的链关系就是Prototypechain原型chain决定了Javascript的继承关系。当我们查找一个属性时,查找机制是这样的:访问对象属性,如果有就返回,通过_proto_去它的原型对象逐层查找,直到找到Object.prototype,如果找到,会返回,如果没有找到,会返回undefind,因为往下看_proto_,有nullInheritanceprototypechainInheritanceprototypechaininheritance通过修改子类的原型为父类的实例,子类可以在父类的原型上传递Access属性和方法孩子。原型=新父()常量子=新子()常量子2=新子(??);child.name='天堂'的孩子。获取名称();//'天堂'child2.获取名称();//'heaven'//'nana'优点:实现简单方便。缺点:父类构造函数中的引用类型(数组/对象)将被所有子类实例共享。当其中一个子类实例被修改时,所有其他子类实例的值将被更改。构造函数继承是通过修改父类构造函数this实现的继承。就是在子类构造函数中执行父类的构造函数,修改父类this为子类this.functionParent(){this.info=['name','age','sex']}functionChild(){Parent.call(this)}constchild=newChild()child.info.push('school')constchild2=newChild()console.log(child,'child');//['姓名','年龄','性别','学校']console.log(child2,'child2');//['name','age','sex']优点:完美解决了上述原型链继承的缺点,修改其中一个子类实例属性值不会影响其他子类。缺点:方法定义在构造函数中,每次都需要重新创建,比较浪费资源。组合继承结合了原型链继承和构造函数继承。functionParent(){this.info=['name','age','sex']}Parent.prototype.getName=function(){returnthis.info;}functionChild(){Parent.call(this)this.topic='fe';}Child.prototype=newParent()Child.prototype.constructor=Childconstchild=newChild()child.info.splice(0,1)constchild2=newChild()console.log(child,'child');console.log(child2,'child');优点:同时解决了构造函数引用类型的问题,避免了方法被多次创建。缺点:父类构造函数被调用两次,子类实例和子类原型对象上都会存在info属性。寄生组合继承在组合继承的基础上,解决了两次调用父类构造函数的问题。functionParent(){this.info=['name','age','sex']}Parent.prototype.getName=function(){returnthis.info;}functionChild(){Parent.call(this)this.topic='fe';}inherit(Child,Parent)functioninherit(child,parent){letprototype=Object(parent.prototype)prototype.constructor=childchild.prototype=prototype}functionobject(o){函数f(){}f.prototype=o;returnnewf()}constchild=newChild()child.info.push('school')constchild2=newChild()console.log(child,'ll');//['姓名','年龄','性别','学校']console.log(child2,'22');//['name','age','sex']优点:是迄今为止实现继承的最合乎逻辑的方式。缺点:比较复杂。ES6继承ES6提供类语法糖和扩展来实现类继承。这也是项目开发中推荐使用的方式。地面类{构造函数(年龄){this.age=age;}lunch(){console.log('吃午饭');}}classPersonextendsGround{constructor(name,age){super(age);这。名字=名字;}drink(){console.log('喝水');}}classStudentextendsPerson{constructor(name,score,age){super(name,age);this.score=得分;};info(){console.log(`我是${this.name},年龄${this.age},得分${this.score}`);}}conststudent=newStudent('张三',19,99)student.info()//我是张三,99岁,19分参考https://juejin.cn/post/684490...https://zhuanlan.zhihu.com/p/...
