最近在面试的时候,遇到过两次问继承实现的几种方式,这里能我给大家列举了以下的这几种,给大家参考参考
这里使用的原理就是在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)
如对本文有疑问, 点击进行留言回复!!
微信小程序wx.scanCode扫描条形码,偶尔出现条形码不正确导致查询失败
Android 入门第七讲01-数据存储(数据存储概述,文件存储(raw和asserts目录读写,data/data/包名目录读写,sdcard目录读写),SharedPreferences读写)
vue-axios系列:axios拦截器,配置请求头,配置请求参数
Vuejs 针对 安卓低版本 、ios9.x 不兼容 ES6语法导致失效解决方法
网友评论