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

原型链与继承

#搞懂还是得自己动手#

原型链

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原型与原型链-腾讯云开发者社区-腾讯云

相关文章:

  • bdf「md」2
  • 【心得】一文梳理高频面试题 HTTP 1.0/HTTP 1.1/HTTP 2.0/HTTP 3.0的区别并附加记忆方法
  • Spring Cloud LoadBalancer详解
  • Raspberry Pi边缘计算网关设计与LoRa通信实现
  • 使用Python SciPy库来计算矩阵的RCS特征值并生成极坐标图
  • 【网络安全 | 扫描子域+发现真实IP】CloakQuest3r安装使用详细教程
  • Python 如何实现烟花效果的完整代码
  • Ollama 的庐山真面目
  • check 单元测试框架
  • 【vue-echarts】——01.认识echarts
  • SVN 简介
  • Java中的CyclicBarrier是什么?
  • 什么是 jQuery
  • 慢sql治理
  • 天锐绿盘 | 文档安全管理系统
  • 【构建企业级Spring Boot应用:从基础到高级的全面指南】
  • 同步类型对比
  • 【每日学点HarmonyOS Next知识】全局调整字体、h5选择框无法取消选中、margin不生效、Length转换为具体值、Prop和link比较
  • 聊一聊 IM 如何优化数据库
  • 16.4 LangChain LCEL 接口全解析:同步、异步与批处理的正确打开方式
  • 手机网站开发+图库类/如何申请百度竞价排名
  • 网站服务费网络建设会计分录/互动营销案例分析
  • wordpress查看浏览量/佛山外贸seo
  • 怎么查网站有没有做404/全球搜索引擎排行榜
  • 蔬菜基地做网站合适吗/搜索引擎优化课程
  • 网站建设存在风险/阐述网络营销策略的内容