首页 > 教程
原型继承和 Class 继承
- 2025-04-07
- 798 ℃
⾸先先来讲下 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上传图片到个人百度网盘
心中无码,自然高清
能自动帮你过人机验证的工具
将浏览器窗口变成简单的...
PHP上传URL地址网络文件...
知网文献免费下载、论文...
如果你也想做公众号挣钱
-
知乎热榜API、百度热点API、微博热搜API(开源)- 聚合热榜API开源
2025-04-07 1202
-
解析PHP中的extract()函数
2021-05-10 1496
-
中毒的分类和诊断
2024-06-18 1067
-
有没有好用的清理手机垃圾的软件呢
2025-03-10 1538
-
从c++魔板算法开始研究加密算法的基础
2025-04-08 989
-
大学可以不用买学校订的教材
2024-11-18 1622
-
Astro 添加 Waline 评论组件
2025-04-07 1305
-
JQUERY判断一个元素是否在可视区域中
2024-03-20 1345
-
jQuery点击生成二维码QRCode复制链接保存到本地
2024-03-06 1013
-
H5页面移动端软键盘弹出时,底部absolute或者fixed定位被顶上去
2024-03-02 1579
文章评论 (0)
- 这篇文章还没有收到评论,赶紧来抢沙发吧~


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