原型链与继承

#搞懂还是得自己动手#

原型链

javascript 复制代码
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

继承

利用原型实现继承

组合继承

javascript 复制代码
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冗余属性)

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

寄生组合继承

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

相关推荐
Y42582 小时前
本地多语言切换具体操作代码
前端·javascript·vue.js
fruge3 小时前
React 2025 完全指南:核心原理、实战技巧与性能优化
javascript·react.js·性能优化
速易达网络4 小时前
Bootstrap 5 响应式网站首页模板
前端·bootstrap·html
etsuyou4 小时前
js前端this指向规则
开发语言·前端·javascript
lichong9514 小时前
Android studio 修改包名
android·java·前端·ide·android studio·大前端·大前端++
cai_huaer4 小时前
BugKu Web渗透之 cookiesWEB
前端·web安全
lichong9514 小时前
Git 检出到HEAD 再修改提交commit 会消失解决方案
java·前端·git·python·github·大前端·大前端++
友友马5 小时前
『 QT 』QT控件属性全解析 (一)
开发语言·前端·qt
不想上班只想要钱5 小时前
vue3+vite创建的项目,运行后没有 Network地址
前端·javascript·vue.js
流***陌6 小时前
手办盲盒抽赏小程序前端功能设计:兼顾收藏需求与抽赏乐趣
前端·小程序