首页 > 教程
原型继承和 Class 继承
- 2025-04-07
- 842 ℃
⾸先先来讲下 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经典趣味算法
微信文件传输助手不够用...
H5 端唤醒 win10 消息通知
这些搜索方法可以助你事...
Nginx域名跳转 www跳转和不带www
3个DeepSeek隐藏玩法,99...
除了百度网盘,我们还可...
微信红包改变支付格局的始末
-
app申请支付宝移动支付
2024-05-13 1521
-
微信快速把图片变成表格
2025-06-22 1305
-
可以下载中小学电子教材(教科书)的网站
2024-07-03 2106
-
ChromeAI – 无限量、离线使用的 Chrome Dev 内置 Gemini Nano 大语言模型
2024-07-03 1769
-
无需视频号!不靠微信收藏!实现朋友圈发1分钟以上长视频
2025-04-27 1464
-
如何使用php与数据库进行交互
2024-03-04 1259
-
php上传图片到个人百度网盘
2021-09-01 1528
-
除了百度网盘,我们还可以选择什么网盘
2025-03-10 1125
-
坐骨股骨撞击综合征的MRI诊断价值研究
2024-06-18 1362
-
微信的尊老爱幼模式,关怀模式和青少年模式
2025-06-22 1010
文章评论 (0)
- 这篇文章还没有收到评论,赶紧来抢沙发吧~


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