标签:缺点 原型链 fun 函数 this 构造 col person 实例
最近在面试的时候,遇到过两次问继承实现的几种方式,这里能我给大家列举了以下的这几种,给大家参考参考
这里使用的原理就是在Child里面,把Parent的this指向改为是Child的this指向,从而实现继承
function Parent(name){ this.name=name; } Parent.prototype.saiHi=function(){ console.log("hello") } function Child(name,age,gender){ Parent.call(this,name) this.age=age; this.gender=gender; } let child=new Child("王磊",20,"男") console.log(child.name);// 王磊 child.sayHi(); // Uncaught TypeError:child.sayHi is not a function
第二种方式就是把Child的原型改为是Parent的实例,从而实现继承
function Parent(name,gender){ this.name=name; this.gender=gender; this.list=[1,2,3] } Parent.prototype.eat=function(){ console.log("晚餐时间到") } function Child(age){ this.age=age; } Child.prototype=new Parent("李白","男"); var child=new Child(20); var child2=new Child(30); child.eat(); console.log(child.list,child2.list);// [1,2,3] [1,2,3] child.list.push(4) console.log(child.list);// [1,2,3,4] console.log(child2.list);// [1,2,3,4]
方式三的话是结合了方式一和方式二来实现继承
function Person(school){ this.school=school; } Person.prototype.skill=function(){ console.log("学习"); } function Student(school,name,age,gender){ Parent.call(this,school); this.name=name; this.age=age; this.gender=gender; } Student.prototype=Person.prototype; let student=new Student("广铁一中","王菲菲",14,"女"); console.log(Student.prototype===Person.prototype) console.log(student.constructor)
function Parent(name,play){ this.name=name; this.play=play; } function Child(name,play,age){ Parent.call(this,name,play); this.age=age; } Child.prototype=Parent.prototype; let child=new Child("张三","玩",20); let child2=new Child("李四","吃",10) console.log(child,child2) console.log(child.prototype===child2.prototype); true console.log(child.constructor); // 构造函数指向的是Parent
只是这种方式的话,你必须得理解Object.create()方法的使用,他创建的对象是在原型上面的
function Parent(name,play){ this.name=name; this.play=play; } function Child(name,play,age){ Parent.call(this,name,play); this.age=age; } Child.prototype=Object.create(Parent.prototype);// 隔离了父类和子类的构造函数,父类的添加到了__proto__属性上 Child.prototype.constructor=Child let child=new Child("张三","玩",20); let child2=new Child("李四","吃",10) console.log(child.constructor)
标签:缺点 原型链 fun 函数 this 构造 col person 实例
原文地址:https://www.cnblogs.com/cythia/p/11175343.html