开封市网站建设_网站建设公司_改版升级_seo优化
2026/1/16 4:40:45 网站建设 项目流程

一句话总览

JavaScript 的继承本质只有一种:原型链
其他所有方式,都是围绕它的不同组合方案。

一、原型链继承
function Parent() {
this.name = 'parent'
}

Parent.prototype.say = function () {}

function Child() {}

Child.prototype = new Parent()

特点

✅ 方法可复用

❌ 父类引用属性会被共享

❌ 无法向父构造函数传参

二、构造函数继承(借用构造函数)
function Parent(name) {
this.name = name
}

function Child(name) {
Parent.call(this, name)
}

特点

✅ 可以传参

✅ 不共享引用属性

❌ 方法不能复用(每个实例一份)

三、组合继承
function Parent(name) {
this.name = name
}

Parent.prototype.say = function () {}

function Child(name) {
Parent.call(this, name)
}

Child.prototype = new Parent()
Child.prototype.constructor = Child

特点

✅ 综合前两者优点

❌ 父构造函数被调用两次

四、原型式继承(Object.create)
const parent = {
say() {}
}

const child = Object.create(parent)

特点

✅ 简单

❌ 共享引用属性

❌ 不适合复杂对象

五、寄生式继承
function createChild(obj) {
const child = Object.create(obj)
child.extra = 'xxx'
return child
}

特点

原型式继承的增强版

实用性有限

六、寄生组合继承(ES5 最优解)
function Parent(name) {
this.name = name
}

Parent.prototype.say = function () {}

function Child(name) {
Parent.call(this, name)
}

Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child

特点

✅ 只调用一次 Parent

✅ 方法共享

✅ 不共享引用属性

七、class extends(现代写法)
class Parent {
constructor(name) {
this.name = name
}
say() {}
}

class Child extends Parent {
constructor(name) {
super(name)
}
}

本质

extends → 原型链

super → Parent.call(this)

属于语法糖

八、对比总结表
方式 复用方法 传参 共享引用 推荐度
原型链 ✅ ❌ ✅ ❌
构造函数 ❌ ✅ ❌ ❌
组合 ✅ ✅ ❌ ⚠️
原型式 ✅ ❌ ✅ ❌
寄生 ⚠️ ❌ ✅ ❌
寄生组合 ✅ ✅ ❌ ✅
class ✅ ✅ ❌ ⭐⭐⭐
九、工程结论

现代开发:class extends

面试本质:继承 = 原型链

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询