首页 > 教程
原型继承和 Class 继承
- 2025-04-07
- 953 ℃
⾸先先来讲下 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正则常用校验大全
相关内容
人人都是增长黑客
带你了解并熟用Deepseek
微信快速把图片变成表格
网站访问量和服务器带宽...
office的安装与激活?保...
php数组函数
去美国必备口语推荐
电脑必装软件有哪些?请...
-
Final Cut Pro X软件或FCPX插件程序已损坏/不明开发者的解决方法 – 苹果电脑怎样设置允许任何来源
2024-08-06 1573
-
jquery获取当前年月日时间和星期
2021-06-02 854
-
class中函数的this指向
2025-04-07 1071
-
阿里云盘达人计划快速升3级指南
2024-05-31 1763
-
JS正则常用校验大全
2025-04-07 1131
-
如何给你的产品做减法
2024-05-29 1483
-
拒绝软件捆绑,这些电脑软件下载网站你知道吗
2025-03-10 1830
-
微信必须关闭那些不该花钱的功能
2025-06-22 1275
-
从c++魔板算法开始研究加密算法的基础
2025-04-08 1131
-
Duplicate Cleaner Pro 重复文件查找清理工具
2021-07-16 1437
文章评论 (0)
- 这篇文章还没有收到评论,赶紧来抢沙发吧~


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