当前位置: 首页 > news >正文

Js实现继承的6种方式

JavaScript 中实现继承的 6 种方式包括:

  1. 原型链继承
  2. 借用构造函数继承
  3. 组合继承(原型链 + 借用构造函数)
  4. 原型式继承
  5. 寄生式继承
  6. 寄生组合式继承

下面是每种方式的详细代码示例:

1. 原型链继承
javascriptfunction Parent() {
this.name = 'Parent';
this.play = [1, 2, 3];
}function Child() {
this.type = 'Child';
}Child.prototype = new Parent(); // Child 继承 Parentlet child1 = new Child();
let child2 = new Child();console.log(child1.name); // Parent
console.log(child1.play === child2.play); // true
2. 借用构造函数继承
javascriptfunction Parent() {
this.name = 'Parent';
this.play = [1, 2, 3];
}function Child() {
Parent.call(this); // 借用 Parent 构造函数
this.type = 'Child';
}let child1 = new Child();
let child2 = new Child();console.log(child1.name); // Parent
console.log(child1.play === child2.play); // false
3. 组合继承(原型链 + 借用构造函数)
javascriptfunction Parent() {
this.name = 'Parent';
this.play = [1, 2, 3];
}function Child() {
Parent.call(this); // 借用 Parent 构造函数
this.type = 'Child';
}Child.prototype = new Parent(); // Child 继承 Parent 的原型链
Child.prototype.constructor = Child; // 修复构造函数指向let child1 = new Child();
let child2 = new Child();console.log(child1.name); // Parent
console.log(child1.play === child2.play); // true
4. 原型式继承
javascriptfunction object(o) {
function F() {}
F.prototype = o;
return new F();
}let parent = {
name: 'Parent',
play: [1, 2, 3]
};let child = object(parent);
child.type = 'Child';console.log(child.name); // Parent
console.log(child.play === parent.play); // true
5. 寄生式继承
javascriptfunction createAnother(original) {
let clone = object(original); // 通过原型式继承创建对象
clone.sayHello = function() {
console.log('Hello from clone');
};
return clone;
}let parent = {
name: 'Parent',
play: [1, 2, 3]
};let child = createAnother(parent);
child.type = 'Child';console.log(child.name); // Parent
console.log(child.play === parent.play); // true
child.sayHello(); // Hello from clone
6. 寄生组合式继承
javascriptfunction inheritPrototype(child, parent) {
let F = function() {};
F.prototype = parent.prototype;
child.prototype = new F();
child.prototype.constructor = child;
}function Parent() {
this.name = 'Parent';
this.play = [1, 2, 3];
}function Child() {
Parent.call(this);
this.type = 'Child';
}inheritPrototype(Child, Parent);let child1 = new Child();
let child2 = new Child();console.log(child1.name); // Parent
console.log(child1.play === child2.play); // false

以上示例展示了 JavaScript 中实现继承的 6 种方式。每种方式都有其特点和应用场景,可以根据具体需求选择合适的方式来实现继承。


http://www.mrgr.cn/news/22447.html

相关文章:

  • 一文彻底搞懂:Java基本数据类型详解
  • C++11 atomic和内存序
  • 谈谈ES搜索引擎
  • 2409wtl,网浏包装
  • 前端页面加载由模糊到清晰的实现方案
  • 生信代码入门:从零开始掌握生物信息学编程技能
  • 使用 BentoML快速实现Llama-3推理服务
  • SpringMVC基础
  • 人工智能领域的微调指的是什么?
  • 如何选择开源云服务
  • PostgreSQL技术内幕9:PostgreSQL事务原理解析
  • 小琳AI课堂:深入学习Transformer模型
  • c++进阶——unordered的封装
  • 【Jupyter Notebook】更改代码默认保存路径
  • 【EI会议征稿通知】第十一届机械工程、材料和自动化技术国际会议(MMEAT 2025)
  • Android 12 SystemUI下拉状态栏禁止QuickQSPanel展开
  • context canceled 到底谁在作祟?
  • 成为优秀程序员-代码篇
  • 野火霸天虎V2学习记录
  • JDBC详细知识点和操作