首页 > 教程
原型继承和 Class 继承
- 2025-04-07
- 876 ℃
⾸先先来讲下 class ,其实在 JS 中并不存在类, class 只是语法糖,本质还是函数
class Person {}
Person instanceof Function; // true组合继承
function Parent(value) {
this.val = value;
}
Parent.prototype.getValue = function () {
console.log(this.val);
};
function Child(value) {
Parent.call(this, value);
}
Child.prototype = new Parent();
const child = new Child(1);
child.getValue(); // 1
child instanceof Parent; // true以上继承的⽅式核⼼是在⼦类的构造函数中通过 Parent.call(this) 继承⽗类的属性, 然后改变⼦类的原型为 new Parent() 来继承⽗类的函数。 这种继承⽅式优点在于构造函数可以传参,不会与⽗类引⽤属性共享,可以复⽤⽗类的函 数,但是也存在⼀个缺点就是在继承⽗类函数的时候调⽤了⽗类构造函数,导致⼦类的原 型上多了不需要的⽗类属性,存在内存上的浪费
寄⽣组合继承
这种继承⽅式对组合继承进⾏了优化,组合继承缺点在于继承⽗类函数时调⽤了构造函数,我们只需要优化掉这点就⾏了
function Parent(value) {
this.val = value;
}
Parent.prototype.getValue = function () {
console.log(this.val);
};
function Child(value) {
Parent.call(this, value);
}
Child.prototype = Object.create(Parent.prototype, {
constructor: {
value: Child,
enumerable: false,
writable: true,
configurable: true,
},
});
const child = new Child(1);
child.getValue(); // 1
child instanceof Parent; // trueclass继承
class Parent {
constructor(value) {
this.val = value;
}
getValue() {
console.log(this.val);
}
}
class Child extends Parent {
constructor(value) {
super(value);
this.val = value;
}
}
let child = new Child(1);
child.getValue(); // 1
child instanceof Parent; // true上一篇:JS压缩图片并保留图片元信息
下一篇:JS正则常用校验大全
相关内容
(PHP)Redis Hash(哈希)操作
如何与竞争对手合作
HTML清除浮动的几种方法
摄影专业分享摄影技巧
jQuery点击生成二维码QRC...
php结合redis实现高并发...
如何给你的产品做减法
微信聊天记录迁移
-
心中无码,自然高清
2025-03-10 1424
-
微信商户号申请
2024-05-13 1543
-
ChatGPT-4o怎么免费使用?含Mac客户端、免费ChatGPT-4o服务
2025-03-04 1527
-
微信最致命的查岗功能,查对象往祖坟上刨
2025-06-22 1437
-
微软超逼真的、带神经网络的中文 TTS怎么使用
2025-04-27 2951
-
什么是Web 3.0 ?
2024-05-10 1463
-
批量提取word文档标题
2025-04-08 1331
-
Wireshark - 网络抓包工具截取并分析各种网络数据包
2025-06-16 1173
-
宝塔面板如何免费使用专业版插件
2024-07-10 2095
-
H5页面移动端软键盘弹出时,底部absolute或者fixed定位被顶上去
2024-03-02 1688
文章评论 (0)
- 这篇文章还没有收到评论,赶紧来抢沙发吧~


进入有缘空间
点击分享文章