首页 > 教程
原型继承和 Class 继承
- 2025-04-07
- 1036 ℃
⾸先先来讲下 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正则常用校验大全
相关内容
公众号主体变更后,批量...
微信让女朋友无法删除拉...
如何删除电脑中超大文件
为什么我国没有ChatGPT那...
查对象手机必备的一招:...
有没有好用的清理手机垃...
什么是暗网,暗网不是冒...
使用电脑一定要学会的20...
-
Fetch的GET、POST简单HTTP请求封装
2025-04-07 1139
-
office的安装与激活?保姆级教程请查收
2025-03-10 1794
-
PHP上传URL地址网络文件到服务器
2025-04-07 1270
-
ChatGPT与AI绘画的本质
2024-05-10 1356
-
黑客万能优盘,自动破解并获取保密数据到U盘
2025-06-16 1729
-
拒绝软件捆绑,这些电脑软件下载网站你知道吗
2025-03-10 1938
-
jquery获取当前年月日时间和星期
2021-06-02 944
-
测试了一堆远程控制工具,发现最好用的原来是它
2025-04-27 1398
-
不备案可以在微信中直接打开的域名后缀
2024-03-04 3316
-
为什么我国没有ChatGPT那样强大的AI智能系统
2024-03-16 1601
文章评论 (0)
- 这篇文章还没有收到评论,赶紧来抢沙发吧~


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