JS 继承有几种方式?

1. 原型链继承

核心思路: 让子类的 prototype 指向父类实例。

js 复制代码
function Parent() {
  this.name = 'Parent'
}
Parent.prototype.sayHello = function () {
  console.log('Hello from Parent')
}

function Child() {}
Child.prototype = new Parent() // 继承 Parent
Child.prototype.constructor = Child

const child = new Child()
console.log(child.name) // "Parent"
child.sayHello() // "Hello from Parent"

优点: 父类方法可复用 ❌ 缺点: 1. 共享引用类型属性(如 arr = [] 会被多个实例共享),2. 无法向父类构造函数传参

2. 借用构造函数继承

核心思路: 在子类构造函数中使用 call 继承父类属性。

js 复制代码
function Parent(name) {
  this.name = name
}
function Child(name, age) {
  Parent.call(this, name) // 继承 Parent
  this.age = age
}
const child = new Child('Rain', 18)
console.log(child.name, child.age) // "Rain", 18

优点: 1. 解决原型链继承共享问题,2. 可传参 ❌ 缺点: 无法继承父类原型上的方法

3. 组合继承(原型链 + 构造函数继承,最常用)

核心思路: 结合前两种方式,继承属性用构造函数,继承方法用原型链

js 复制代码
function Parent(name) {
  this.name = name
}
Parent.prototype.sayHello = function () {
  console.log('Hello from Parent')
}

function Child(name, age) {
  Parent.call(this, name) // 第 1 次调用 Parent
  this.age = age
}

Child.prototype = new Parent() // 第 2 次调用 Parent
Child.prototype.constructor = Child

const child = new Child('Rain', 18)
console.log(child.name, child.age) // "Rain", 18
child.sayHello() // "Hello from Parent"

优点: 解决了前两种方法的缺陷 ❌ 缺点: 调用两次 Parent 构造函数(一次 call,一次 Object.create()

4. Object.create() 继承(原型式继承)

核心思路: 直接用 Object.create() 创建一个新对象,继承已有对象。

js 复制代码
const parent = {
  name: 'Parent',
  sayHello() {
    console.log('Hello!')
  },
}
const child = Object.create(parent)
child.age = 18
console.log(child.name, child.age) // "Parent", 18
child.sayHello() // "Hello!"

优点: 适合创建对象而非类的继承 ❌ 缺点: 不能传参,只适用于简单继承

5. 寄生组合继承(优化版,推荐)

核心思路: 组合继承的优化版本 ,避免了 Parent 被调用两次的问题。

js 复制代码
function Parent(name) {
  this.name = name
}
Parent.prototype.sayHello = function () {
  console.log('Hello from Parent')
}

function Child(name, age) {
  Parent.call(this, name)
  this.age = age
}
Child.prototype = Object.create(Parent.prototype) // 关键优化
Child.prototype.constructor = Child

const child = new Child('Rain', 18)
console.log(child.name, child.age) // "Rain", 18
child.sayHello() // "Hello from Parent"

优点: 1. 继承属性和方法,2. 只调用一次 Parent缺点: 代码略微复杂

相关推荐
蒙面价肥猫1 天前
Flex布局-彻底掌握 flex-grow / flex-shrink / flex-basis
前端·css·css3
DsirNg1 天前
上一个封装hooks涉及的知识学习路线
前端·javascript·typescript
遇到困难睡大觉哈哈1 天前
Harmony os ArkTS 卡片生命周期管理:我怎么把 EntryFormAbility 用顺手的
前端·harmonyos·鸿蒙
凌览1 天前
女朋友换头像比翻书快?我3天肝出一个去水印小程序
前端·后端·面试
IT_陈寒1 天前
3个90%开发者都误解的JavaScript原型陷阱:从proto到class的深度剖析
前端·人工智能·后端
9***44631 天前
Spring 核心技术解析【纯干货版】- Ⅶ:Spring 切面编程模块 Spring-Instrument 模块精讲
前端·数据库·spring
tsumikistep1 天前
【前端】md5 加密算法
前端
拾忆,想起1 天前
Dubbo服务调用失败调试指南:从问题定位到快速修复
前端·微服务·架构·dubbo·safari
Json____1 天前
uni-app-数码购物商城h5手机端-前端静态网页
前端·uni-app·商城
k***85841 天前
删除文件夹,被提示“需要来自 TrustedInstaller 的权限。。。”的解决方案
android·前端·后端