JavaScript 原型(Prototype)详解

发布于:2025-06-15 ⋅ 阅读:(19) ⋅ 点赞:(0)

在 JavaScript 中,prototype(原型) 是实现继承的核心机制,它是每个 JavaScript 对象都拥有的内置属性,用于共享属性和方法。

核心概念

1. 原型是什么?

  • 每个 JavaScript 函数都有一个特殊的 prototype 属性(函数也是对象)
  • 这个 prototype 属性是一个对象,称为"原型对象"
  • 当使用 new 关键字创建实例时,实例会继承其构造函数的原型对象

2. 原型链如何工作?

function Person(name) {
    this.name = name;
}

// 向原型添加方法
Person.prototype.greet = function() {
    return `Hello, I'm ${this.name}`;
};

const alice = new Person("Alice");

// 当访问 alice.greet() 时:
// 1. 先检查 alice 对象自身是否有 greet 方法 → 没有
// 2. 然后检查 alice.__proto__ (指向 Person.prototype) → 找到并执行
console.log(alice.greet()); // "Hello, I'm Alice"

3. 原型链可视化

alice 实例
  │
  ├── 自身属性: name = "Alice"
  │
  └── __proto__ 指向 → Person.prototype
        │
        ├── greet() 方法
        │
        └── __proto__ 指向 → Object.prototype
               │
               ├── toString() 方法
               ├── hasOwnProperty() 方法
               │
               └── __proto__ 指向 → null

关键属性和方法

1. prototype 属性

  • 存在于构造函数上
  • 用于定义将被所有实例继承的属性和方法
function Car(model) {
    this.model = model;
}

// 向 Car 的原型添加方法
Car.prototype.drive = function() {
    return `${this.model} is driving`;
};

2. _ _ proto _ _ 属性(已弃用但广泛支持)

  • 存在于对象实例上
  • 指向创建该对象的构造函数的 prototype
  • 现代代码应使用 Object.getPrototypeOf()
const myCar = new Car("Tesla");
console.log(myCar.__proto__ === Car.prototype); // true
console.log(Object.getPrototypeOf(myCar) === Car.prototype); // true (推荐)

3. constructor 属性

  • 存在于原型对象上
  • 指回构造函数本身
console.log(Car.prototype.constructor === Car); // true
console.log(myCar.constructor === Car); // true (通过原型链访问)

原型继承实践

1. 基本继承实现

// 父类
function Animal(name) {
    this.name = name;
}

Animal.prototype.eat = function() {
    return `${this.name} is eating`;
};

// 子类
function Dog(name, breed) {
    Animal.call(this, name); // 调用父类构造函数
    this.breed = breed;
}

// 设置原型链继承
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // 修复构造函数指向

// 添加子类特有方法
Dog.prototype.bark = function() {
    return `${this.name} barks loudly!`;
};

// 使用
const myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.eat()); // "Buddy is eating" (继承自 Animal)
console.log(myDog.bark()); // "Buddy barks loudly!" (自有方法)

2. ES6 类语法(基于原型的语法糖)

class Animal {
    constructor(name) {
        this.name = name;
    }
    
    eat() {
        return `${this.name} is eating`;
    }
}

class Dog extends Animal {
    constructor(name, breed) {
        super(name); // 调用父类构造函数
        this.breed = breed;
    }
    
    bark() {
        return `${this.name} barks loudly!`;
    }
}

const myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.eat()); // 继承方法
console.log(myDog.bark()); // 自有方法

原型相关的重要方法

1. Object.create()

创建一个新对象,使用现有对象作为新对象的原型

const animalPrototype = {
    eat() {
        return `${this.name} is eating`;
    }
};

const rabbit = Object.create(animalPrototype);
rabbit.name = "Bunny";
console.log(rabbit.eat()); // "Bunny is eating"

2. Object.getPrototypeOf()

获取对象的原型

console.log(Object.getPrototypeOf(rabbit) === animalPrototype); // true

3. Object.setPrototypeOf()

设置对象的原型(不推荐在性能敏感代码中使用)

const bird = { name: "Tweety" };
Object.setPrototypeOf(bird, animalPrototype);
console.log(bird.eat()); // "Tweety is eating"

4. instanceof 操作符

检查对象是否在原型链中包含指定构造函数的原型

console.log(myDog instanceof Dog); // true
console.log(myDog instanceof Animal); // true
console.log(myDog instanceof Object); // true

原型的重要性

  1. 共享方法:所有实例共享原型上的方法,节省内存
  2. 动态更新:修改原型会影响所有已存在的实例
  3. 实现继承:JavaScript 中继承的核心机制
  4. 多态支持:通过原型链实现方法覆盖
// 动态更新示例
Animal.prototype.sleep = function() {
    return `${this.name} is sleeping`;
};

console.log(myDog.sleep()); // "Buddy is sleeping" (即使实例已创建)

理解 JavaScript 的原型机制是掌握这门语言面向对象编程的关键。虽然 ES6 类语法提供了更直观的接口,但其底层实现仍然基于原型继承。