技术文摘
如何实现js继承
2025-01-09 12:16:38 小编
如何实现js继承
在JavaScript中,继承是一种强大的特性,它允许对象继承其他对象的属性和方法,有助于代码的复用和结构优化。以下将介绍几种常见的实现JavaScript继承的方式。
原型链继承
这是JavaScript中最基本的继承方式。每个对象都有一个内部属性 [[Prototype]],它指向该对象的原型对象。当访问一个对象的属性或方法时,JavaScript首先会在对象本身查找,如果找不到,就会沿着原型链向上查找。
function Parent() {
this.parentProperty = 'I am a parent property';
this.parentMethod = function() {
console.log('This is a parent method');
};
}
function Child() {}
Child.prototype = new Parent();
let child = new Child();
child.parentMethod();
构造函数继承
通过在子类构造函数中调用父类构造函数,使用 this 关键字将父类的属性和方法复制到子类实例中。
function Parent(name) {
this.name = name;
this.sayName = function() {
console.log('My name is'+ this.name);
};
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
let child = new Child('Tom', 10);
child.sayName();
组合继承
结合了原型链继承和构造函数继承的优点。通过原型链实现方法的继承,通过构造函数实现属性的继承。
function Parent(name) {
this.name = name;
this.sayName = function() {
console.log('My name is'+ this.name);
};
}
Parent.prototype.sayHello = function() {
console.log('Hello from parent');
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
let child = new Child('Jerry', 12);
child.sayName();
child.sayHello();
寄生组合继承
对组合继承的优化,避免了在创建子类原型时不必要的父类实例创建。
function Parent(name) {
this.name = name;
this.sayName = function() {
console.log('My name is'+ this.name);
};
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
function inheritPrototype(subType, superType) {
let prototype = Object.create(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
inheritPrototype(Child, Parent);
let child = new Child('Bob', 15);
child.sayName();
掌握这些继承方式,能让开发者在不同的应用场景中,灵活运用以实现高效、可维护的代码结构,提升JavaScript编程的效率与质量。
- 库里Curry拥有几百个表,令人震惊!
- 程序员提升阅读代码水平的若干途径
- Python 构建云服务与小程序“云办公”
- Redis Labs 更名 Redis:纯粹简约
- CSS 颜色属性的优秀设置方法有哪些
- 提升 SwiftUI 列表灵活性的方法
- HashMap 竟也存在懒加载?
- JetBrains 技术布道师范圣佑:从程序员的蜕变成长
- 开发语言能否统一为一种?令人恼火!
- C 语言最大难点剖析:编程中的阻碍
- JS 卡片开发的代码示例工程 JsFACard 与 StepsCard 解析
- ACE JS 框架如何实现单线程开发异步任务
- 五分钟轻松体验分布式事务
- 面试官:宝子,setState 是同步还是异步?
- Springboot 与 Kafka Stream 整合实现实时数据统计