JavaScript原型链_继承机制与类设计模式

JavaScript继承基于原型链,对象通过[[Prototype]]链接向上查找属性;ES6 class为语法糖,底层仍为原型继承。

JavaScript 的继承机制不同于传统的面向对象语言,它基于原型链(Prototype Chain)实现。虽然 ES6 引入了 class 语法糖,让代码看起来更接近类式语言,但底层依然是原型继承。理解原型链是掌握 JavaScript 面向对象编程的关键。

原型与原型链:核心机制

在 JavaScript 中,每个对象都有一个内部属性 [[Prototype]],指向其原型对象。这个链接构成了“原型链”:

  • 对象通过 [[Prototype]] 链向上查找属性和方法
  • 函数除了有 [[Prototype]],还有 prototype 属性,用于构造实例时指定其原型
  • 当访问一个对象的属性时,若自身没有,会沿原型链逐级查找,直到 Object.prototype 或 null

例如:

function Person(name) {
  this.name = name;
}
Person.prototype.greet = function() {
  return "Hello, I'm " + this.name;
};

const alice = new Person("Alice");
console.log(alice.greet()); // "Hello, I'm Alice"
// alice → Person.prototype → Object.prototype → null

继承的实现方式

JavaScript 提供多种方式模拟继承,以下是常见模式:

1. 原型链继承

将子类的 prototype 指向父类的实例:

function Child() {}
Child.prototype = new Parent();

缺点:所有实例共享引用类型属性,无法向父类传参。

2. 构造函数继承(借用构造函数)

在子类构造中调用父类构造函数:

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

优点:可传参,避免引用共享。缺点:无法继承原型上的方法。

3. 组合继承(常用)

结合前两者,最通用的模式:

function Child(name, age) {
  Parent.call(this, name); // 继承实例属性
  this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // 修正构造器

既继承了实例属性,也继承了原型方法。

4. ES6 Class 继承

使用 classextends 语法,更清晰简洁:

class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hello, I'm ${this.name}`;
  }
}

class Student extends Person {
  constructor(name, grade) {
    super(name);
    this.grade = grade;
  }
  study() {
    return `${this.name} is studying.`;
  }
}

底层仍是原型链,但语义更强,推荐在现代项目中使用。

类设计模式的应用

基于原型机制,可以实现常见设计模式:

工厂模式

封装对象创建过程,返回带有方法的对象:

function createUser(name) {
  return {
    name,
    greet() { return `Hi, I'm ${this.name}`; }
  };
}
单例模式

确保一个类仅有一个实例:

class Logger {
  constructor() {
    if (Logger.instance) return Logger.instance;
    Logger.instance = this;
    this.logs = [];
  }
  log(msg) { this.logs.push(msg); }
}