2026-10-25 00:46:50
JavaScript 的原型(prototype)是实现对象继承和属性共享的核心机制,通过原型链实现方法复用和动态扩展。以下是详细解析:
1. 原型的核心概念通过 prototype 添加的方法会被所有实例共享,避免重复定义。
Person.prototype.greet = function() { console.log(`Hello, ${this.name}`);};person.greet(); // 输出: Hello, Alice添加共享属性动态修改原型会影响所有实例(包括已创建的实例)。
Person.prototype.species = 'Homo Sapiens';console.log(person.species); // 输出: Homo Sapiens3. 原型链机制当访问对象的属性或方法时,JavaScript 会按以下顺序查找:
创建新对象并指定其原型(不依赖构造函数):
const anotherPerson = Object.create(Person.prototype);anotherPerson.name = 'Bob';anotherPerson.greet(); // 输出: Hello, Bob检查属性来源通过原型实现继承(ES5 方式):
function Student(name, grade) { Person.call(this, name); // 继承属性 this.grade = grade;}Student.prototype = Object.create(Person.prototype); // 继承方法Student.prototype.constructor = Student; // 修复构造函数指向const student = new Student('Charlie', 'A');student.greet(); // 输出: Hello, Charlie总结掌握原型机制是深入理解 JavaScript 面向对象编程的关键!