技术文摘
如何实现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编程的效率与质量。
- Go 语言的并发和 WorkerPool 机制
- 教妹学 Java :重写 Equals 必重写 HashCode 方法的原因
- 伪类和伪元素究竟为何
- 面试官:React Jsx 如何转换为真实 DOM?
- 分布式存储系统的可靠性量化估算
- Node.js 中 FilePond 的使用方法
- 13 个 Helm 部署应用程序的实践要点
- 前端插件式可扩展架构的设计体会
- Python 竟无像样定时器?试试此方法!
- 20 年一人写出 70 万行代码 沙盒游戏“鼻祖”13 年依赖玩家捐赠存活
- 怎样使你的开源项目更具展现力
- 必试的 10 个奇妙 Python 库
- 前端工程师利用 Nodejs 实现自动发送邮件的方法
- 敏捷开发中的研发流程
- 对 TC39 提案 Module Fragments 的看法