当前位置:网站首页>js-继承
js-继承
2022-04-22 06:29:00 【GeXueliu】
继承
js中的继承是通过原型实现的。
方式一:将原型指向继承对象的原型
function Animal(name) {
this.name =name;
}
Animal.prototype.age = 23;
let a = new Animal('lily');
function People(name) {
this.name = name
}
People.prototype = Animal.prototype; // 指定原型对象为Animal 的原型
let p1 = new People('张三');
console.log(p1.age) // expect output 23 p1继承了age
/*** * 这样做引起一个问题,当修改通过p1 修改Person的原型时,同时也修改了Animal的原型 **/
p1.__proto__.age = 48;
console.log(a.age) // expect output 48 Animal 的原型被修改了

方式二: 指定原型对象为继承对象的一个实例
function Animal(name) {
this.name =name;
}
Animal.prototype.age = 23;
let a = new Animal('lily');
function People(name) {
this.name = name
}
People.prototype = new Animal('dog'); // 继承Animal
let p2 = new People('wangermazi');
p2.__proto__.age = 15;
console.log(a.age) // expect output 23
console.log(p2.age); // expect output 15
/* * 解决了方式一存在的问题,同时方法三也能解决方式一存在的问题 ***/

方式三:使用中转函数
function Animal(name) {
this.name =name;
}
Animal.prototype.age = 23;
let a = new Animal('lily');
function People(name) {
this.name = name
}
function fn() {
}; // 中转函数
fn.prototype = Animal.prototype;
People.prototype = new fn(); // 继承
let p3 = new People('lisi');
p3.__proto__.age = 48
console.log(p3.age) // expect output 48
console.log(a.age) // expect output 23

总结:因此继承一个函数,最好不要使用方式一(直接将原型指向要继承函数的原型)。实现bind函数会用到这个知识点
版权声明
本文为[GeXueliu]所创,转载请带上原文链接,感谢
https://blog.csdn.net/GeXueliu/article/details/124317623
边栏推荐
- Plain CSRF vulnerability
- Wireshark在流量分析中的使用
- A simple image processor running across C raspberry pie
- mysql中查询遇到longtext类型,查询效率很低。
- 树莓派mono上跨平台运行一个C#自制的简易图片处理器
- 在window环境下面virtualbox加载移动硬盘里创建好的虚拟机
- Raspberry pie 4B: USB mobile hard disk box startup (beta version)
- 小菜鸡的学习笔记——sql注入之sqli-lab边学边练
- SuperSocket在.Net5中使用——AppSession和SuperSocketService篇
- OBD外接测试设备初始化判断协议类型(SAE J1939/ISO15765/ISO27145)
猜你喜欢

圣杯布局和双飞翼布局

.Net5 Log4Net启动一段时间后记录日志到数据库中失败问题

SuperSocket在.Net5中使用——WebSocket Server篇

树莓派mono上跨平台运行一个C#自制的简易图片处理器

SSRF 与 XXE 攻击原理及利用

《数据安全法》解读及安全保密技术应用交流会在京成功举办

世平信息参与衡阳市“船山论坛”企业路演,畅谈数据安全,助力协同创新
![RT thread [II] system initialization process](/img/46/6e2942e4c18c0220378050205e6528.png)
RT thread [II] system initialization process

SuperSocket在.Net5中使用——AppSession和SuperSocketService篇

Raspberry pie Lite: install the latest version of discuz
随机推荐
文件上传漏洞小结与Upload-labs 靶场纪实
树莓派:模拟iSCSI存储
网页导入3D模型-obj/mtl文件
mysql查询数据库中所有字段的属性
Read iso15031 protocol data stream
Principle and application of SSRF and xxE attack
Oopc [i] C language objectification
C-10 age issues
树莓派4B:USB移动硬盘盒启动(beta版)
基于卷积神经网络LeNet-5模型的mnist手写数字识别
世平信息成功通过CMMI 3级认定
Continue raspberry pie 4B + OLED: automatically display the IP address after startup
世平信息亮相中国中医药信息大会,助力医药行业数据安全体系建设
Get the current DLL or exe path
读取ISO15031协议数据流
世平信息董事长王世晞荣获2020年度新锐人物奖
About XSS Cross Station
Solve the problem that the message notification is blocked by the El dialog ($message, $alert, $notify, $confirm)
【从零开始写漏扫】主机发现——手写一个子域名挖掘器
简单c语言练习:学生数据的存取