JavaScript继承实现方法详解
时间:2026-03-28
浏览:366
作者:佚名
JavaScript的继承机制本质上基于原型链,虽无传统类语言的原生类继承,但通过原型链、构造函数调用、组合模式及ES6的class语法糖等多种方式实现了灵活而强大的继承能力;文章系统剖析了四种主流实现:原型链继承易导致引用属性污染,构造函数继承确保实例属性独立却无法复用原型方法,组合继承兼顾二者优势成为传统方案首选,而ES6 class配合extends和super则以清晰语法和明确语义成为现代开发的标准实践——无论你是在维护老项目还是构建新应用,理解这些机制背后的原理与取舍,都能帮你写出更健壮、可维护的面向对象JavaScript代码。

JavaScript 的继承机制主要基于原型(prototype)实现,不同于传统面向对象语言的类继承。ES6 引入了 class 语法糖,让继承写法更清晰,但底层仍依赖原型链。
1. 原型链继承(经典方式)
通过将子构造函数的 prototype 指向父构造函数的实例,实现属性和方法的继承。
function Parent() {
this.name = 'parent';
}
Parent.prototype.getName = function() {
return this.name;
};
function Child() {
this.type = 'child';
}
// 继承父类原型
Child.prototype = new Parent();
const c = new Child();
console.log(c.getName()); // 'parent'
缺点:所有子实例共享父类实例,若父类有引用类型属性,一个实例修改会影响其他实例。
2. 构造函数继承(借用构造函数)
在子构造函数中调用父构造函数,绑定 this,可传参。
function Parent(name) {
this.name = name;
this.colors = ['red', 'blue'];
}
function Child(name, age) {
Parent.call(this, name); // 继承并传参
this.age = age;
}
const c1 = new Child('Tom', 12);
const c2 = new Child('Jerry', 10);
c1.colors.push('green');
console.log(c1.colors); // ['red', 'blue', 'green']
console.log(c2.colors); // ['red', 'blue'] —— 不互相影响
缺点:无法继承父类原型上的方法。
3. 组合继承(最常用)
结合原型链和构造函数继承,既继承实例属性,又继承原型方法。
function Parent(name) {
this.name = name;
this.colors = ['red', 'blue'];
}
Parent.prototype.getName = function() {
return this.name;
};
function Child(name, age) {
Parent.call(this, name); // 继承实例属性
this.age = age;
}
Child.prototype = new Parent(); // 继承原型
Child.prototype.constructor = Child; // 修正构造器指向
Child.prototype.getAge = function() {
return this.age;
};
这种方式兼顾了属性独立与方法复用,是传统模式下的推荐做法。
4. ES6 Class 继承(现代写法)
使用 class 和 extends 关键字,语法更直观。
class Parent {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 调用父类构造函数
this.age = age;
}
getAge() {
return this.age;
}
}
const c = new Child('Alice', 15);
console.log(c.getName()); // 'Alice'
console.log(c.getAge()); // 15
这是目前最推荐的方式,代码清晰,语义明确,底层仍是原型继承的封装。
基本上就这些。选择哪种方式取决于项目环境和需求,现代开发建议使用 class 语法。
本篇关于《JavaScript继承实现方法详解》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
