原型链与继承

#搞懂还是得自己动手#

原型链

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

相关推荐
dog shit37 分钟前
web第十次课后作业--Mybatis的增删改查
android·前端·mybatis
我有一只臭臭37 分钟前
el-tabs 切换时数据不更新的问题
前端·vue.js
七灵微41 分钟前
【前端】工具链一本通
前端
Nueuis2 小时前
微信小程序前端面经
前端·微信小程序·小程序
_r0bin_4 小时前
前端面试准备-7
开发语言·前端·javascript·fetch·跨域·class
IT瘾君4 小时前
JavaWeb:前端工程化-Vue
前端·javascript·vue.js
zhang98800004 小时前
JavaScript 核心原理深度解析-不停留于表面的VUE等的使用!
开发语言·javascript·vue.js
potender4 小时前
前端框架Vue
前端·vue.js·前端框架
站在风口的猪11085 小时前
《前端面试题:CSS预处理器(Sass、Less等)》
前端·css·html·less·css3·sass·html5
程序员的世界你不懂5 小时前
(9)-Fiddler抓包-Fiddler如何设置捕获Https会话
前端·https·fiddler