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

原型链与继承

#搞懂还是得自己动手#

原型链

function Person(name) { 
  this.name = name;
}
Person.prototype.sayName = function() { 
  console.log(this.name);
};

const p = new Person("Alice");

原型链关系图:

原型链:person->Person.prototype->Object.prototype->null

继承

利用原型实现继承

组合继承

function Parent(name) {
  this.name = name;
}
Parent.prototype.say = function() {};

function Child(name) {
  Parent.call(this, name); // 第1次调用Parent
}
Child.prototype = new Parent(); // 第2次调用Parent(导致Child.prototype冗余属性)

子类创建一次,父类构造函数需执行两次

寄生组合继承

function inheritPrototype(Child, Parent) {
  const prototype = Object.create(Parent.prototype); // 创建父类原型副本(避免直接引用)
  prototype.constructor = Child; // 修正constructor指向
  Child.prototype = prototype;
}

// 父类
function Parent(name) {
  this.name = name;
}
Parent.prototype.say = function() {};

// 子类
function Child(name, age) {
  Parent.call(this, name); // 仅调用一次父类构造函数
  this.age = age;
}

// 继承原型方法
inheritPrototype(Child, Parent);

// 子类新增方法
Child.prototype.run = function() {};
  • 仅调用一次父类构造函数
  • 子类原型链纯净,无冗余属性
  • 创建中间对象,增加内存开销

参考:彻底搞懂JS原型与原型链-腾讯云开发者社区-腾讯云


http://www.kler.cn/a/572894.html

相关文章:

  • 【RAG 篇】万字长文:向量数据库选型指南 —— Milvus 与 FAISS/Pinecone/Weaviate 等工具深度对比
  • 软考架构师笔记-进程管理
  • 自动驾驶---不依赖地图的大模型轨迹预测
  • AI与.NET技术实操系列
  • Python:函数的各类参数以及函数嵌套
  • Mono里运行C#脚本44—System.Console.WriteLine()函数的生成过程
  • L2-001 紧急救援
  • CS144 Lab Checkpoint 0: networking warm up
  • java数据结构_Map和Set_HashMap 底层源码解读_9.5
  • python量化交易——金融数据管理最佳实践——使用qteasy大批量自动拉取金融数据
  • 前端练习项目:html css js 开发AI数字人平台官网前端静态页面
  • 【AIGC】通义万相 2.1 与蓝耘智算:共绘 AIGC 未来绚丽蓝图
  • 设备管理系统功能与.NET+VUE(IVIEW)技术实现
  • 神经网络之CNN文本识别
  • 在 Docker 中,无法直接将外部多个端口映射到容器内部的同一个端口
  • MyBatis-Plus 条件构造器的使用(左匹配查询)
  • Windows零门槛部署DeepSeek大模型:Ollama+7B参数模型本地推理全攻略
  • alpine linux 系统最新版安装及使用教程
  • 【JAVA面试题】Spring、Spring MVC、Spring Boot、Spring Cloud的区别与联系
  • 2025 ubuntu24.04系统安装docker