技术文摘
JS 实现继承的方式有哪些?
2024-12-31 05:49:19 小编
JS 实现继承的方式有哪些?
在 JavaScript 中,实现继承的方式有多种,每种方式都有其特点和适用场景。
1. 原型链继承
原型链继承是 JavaScript 中最基本的继承方式。通过将子类的原型对象设置为父类的实例,从而实现继承。这种方式简单直观,但存在一些问题,比如多个实例对引用类型的属性修改会相互影响。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello from Parent');
};
function Child() {}
Child.prototype = new Parent();
let child1 = new Child();
child1.sayHello();
2. 借用构造函数继承
借用构造函数继承可以解决原型链继承中引用类型属性共享的问题。在子类的构造函数中通过 call 或 apply 方法调用父类的构造函数。
function Parent(name) {
this.name = name;
}
function Child(name) {
Parent.call(this, name);
}
let child2 = new Child('Child');
console.log(child2.name);
3. 组合继承
组合继承结合了原型链继承和借用构造函数继承的优点。先通过借用构造函数继承实例属性,再通过原型链继承方法。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello from Parent');
};
function Child(name) {
Parent.call(this, name);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
let child3 = new Child('Child');
child3.sayHello();
4. 原型式继承
原型式继承是利用一个空对象作为中介,将某个对象直接赋值给这个空对象的原型,从而实现继承。
function createObject(obj) {
function F() {}
F.prototype = obj;
return new F();
}
5. 寄生式继承
寄生式继承是在原型式继承的基础上,创建一个仅用于增强对象的函数。
function enhanceObject(obj) {
let clone = Object.create(obj);
clone.someMethod = function() {
// 增强的方法
};
return clone;
}
6. 寄生组合式继承
这是目前较为理想的继承方式,解决了组合继承中多次调用父类构造函数的效率问题。
function inheritPrototype(child, parent) {
let prototype = Object.create(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
function Parent() {}
Parent.prototype.sayHello = function() {
console.log('Hello from Parent');
};
function Child() {}
inheritPrototype(Child, Parent);
JavaScript 提供了多种实现继承的方式,开发者可以根据具体的需求和场景选择合适的继承方式,以提高代码的可维护性和可扩展性。
- 一行代码淘汰 Debug 与 Print ,推动算法学习
- React 与 Vue:2022 年最佳框架之争
- 架构师必知:技术架构的数据与应用改进之法
- Filter 与 Backdrop-filter 傻傻分不清?深入解析其异同
- 为何不进行重构?
- Dotnet Core 技术中 Dotnet 6.0 的深度剖析
- Proto 代码的存放位置令人头疼
- 在 Go 中如何将 []byte 转换为 io.Reader
- Vue3 插槽使用全解析
- 快速学会 Performance 性能分析:真实优化实例
- 2022 年 10 个优质 Node.js CMS 平台推荐
- 一同畅玩 ByteBuffer
- LeetCode 中电话号码的字母组合
- 微服务是什么及如何构建
- Top 5 最易学与最难学的编程语言