JavaScript 有哪些继承方式?各有什么优缺点?
1. 原型链继承
function Parent() { this.colors = ['red'] }
Parent.prototype.sayHi = function () {}
function Child() {}
Child.prototype = new Parent()
- ✅ 简单,能继承原型方法
- ❌ 引用类型属性被所有实例共享,无法传参
2. 构造函数继承(call/apply)
function Parent(name) { this.name = name; this.colors = ['red'] }
function Child(name) { Parent.call(this, name) }
- ✅ 解决引用类型共享问题,可传参
- ❌ 无法继承原型上的方法
3. 组合继承(最常用)
function Parent(name) { this.name = name; this.colors = ['red'] }
Parent.prototype.sayHi = function () {}
function Child(name, age) {
Parent.call(this, name)
this.age = age
}
Child.prototype = new Parent()
Child.prototype.constructor = Child
4. 寄生组合继承(最优方案)
function inherit(Child, Parent) {
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
}
function Parent(name) { this.name = name }
Parent.prototype.sayHi = function () {}
function Child(name, age) {
Parent.call(this, name)
this.age = age
}
inherit(Child, Parent)
- ✅ 只调用一次 Parent,原型链正确
- ✅ 最理想的继承方案
5. ES6 class 继承
class Parent {
constructor(name) { this.name = name }
sayHi() { console.log(this.name) }
}
class Child extends Parent {
constructor(name, age) {
super(name)
this.age = age
}
}
- ✅ 语法简洁,本质是寄生组合继承的语法糖
- ✅ 推荐使用
同分类其他题目