2026-10-20 15:59:19
在 JavaScript 中实现继承有多种方式,下面我将从基础到高级逐步讲解,并提供代码示例和图示说明。
一、原型链继承(第一版)核心思想:通过修改子类的原型指向父类实例来实现继承。
function Animal(name) { this.name = name;}Animal.prototype.eat = function() { console.log('eat');};function Cat(name) { Animal.call(this, name); // 继承父类属性}Cat.prototype = new Animal(); // 继承父类方法Cat.prototype.constructor = Cat; // 修正constructor// 测试const tom = new Cat('Tom');console.log(tom.name); // Tomtom.eat(); // eat图示说明:

特点:
核心改进:使用空函数作为中介,避免重复调用父类构造函数。
function Animal(name) { this.name = name;}Animal.prototype.eat = function() { console.log('eat');};function Cat(name) { Animal.call(this, name); // 继承属性}// 关键优化点function inheritPrototype(child, parent) { function F() {} F.prototype = parent.prototype; child.prototype = new F(); child.prototype.constructor = child;}inheritPrototype(Cat, Animal);// 测试const jerry = new Cat('Jerry');console.log(jerry.name); // Jerryjerry.eat(); // eat图示说明:

优点:
现代语法:使用extends和super关键字。
class Animal { constructor(name) { this.name = name; } eat() { console.log('eat'); }}class Cat extends Animal { constructor(name) { super(name); // 必须调用super }}// 测试const kitty = new Cat('Kitty');console.log(kitty.name); // Kittykitty.eat(); // eat特点:
继承内置对象(如Array)的特殊处理
静态属性和方法的继承
new.target的使用
通过以上方法,你可以根据项目需求选择最适合的继承实现方式。ES6的class语法是最推荐的方式,它提供了最清晰直观的继承实现方式。