内部原理具体可参考:limeii.github.io/2019/05/js-…
原型链(Prototype Chain)是什么?
原型链是 JavaScript 继承机制的基础,它通过 prototype 让对象继承其他对象的属性和方法。
它是基于对象之间的原型关系构建的。
JavaScript 对象有一条指向原型对象的链。当试图访问对象的属性时,不仅在该对象上查找属性,还会在该对象的原型上查找属性,以及原型的原型,依此类推,直到找到一个名字匹配的属性或到达原型链的末尾。
1. 原型(Prototype)
在 JavaScript 中,每个对象都有一个隐藏的 [[Prototype]](可以用 __proto__ 访问)。
如果访问一个对象的属性或方法,JavaScript 先在自身查找,如果找不到,就沿着原型链向上查找。
示例
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
const p1 = new Person("Alice");
p1.sayHello(); // ✅ Hello, my name is Alice
console.log(p1.__proto__ === Person.prototype); // ✅ true
console.log(Person.prototype.__proto__ === Object.prototype); // ✅ true
console.log(Object.prototype.__proto__); // ✅ null (原型链的顶端)
🔹 p1 找不到 sayHello,于是沿着原型链查找 Person.prototype,成功调用方法。
2. 原型链的结构
在 JavaScript 中,所有对象都最终继承自 Object.prototype:
p1 --> Person.prototype --> Object.prototype --> null
p1.__proto__指向Person.prototypePerson.prototype.__proto__指向Object.prototypeObject.prototype.__proto__为null(表示原型链的终点)
如果一个对象在整个原型链中都找不到属性,就返回 undefined。
3. 原型链的继承
子类可以继承父类的方法:
function Student(name, grade) {
Person.call(this, name); // 继承属性
this.grade = grade;
}
// 继承 Person 的方法
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
const s1 = new Student("Bob", "7th Grade");
s1.sayHello(); // ✅ Hello, my name is Bob
console.log(s1.__proto__ === Student.prototype); // ✅ true
console.log(Student.prototype.__proto__ === Person.prototype); // ✅ true
🔹 s1 找不到 sayHello,于是沿着原型链查找 Student.prototype,再往上查找 Person.prototype,最终找到并调用 sayHello。
4. 现代写法:class 继承
ES6 class 语法让继承更清晰:
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
}
class Student extends Person {
constructor(name, grade) {
super(name); // 继承属性
this.grade = grade;
}
}
const s2 = new Student("Charlie", "8th Grade");
s2.sayHello(); // ✅ Hello, my name is Charlie
🔹 Student 继承 Person,但原型链机制本质上不变。
5. 总结
✅ 原型链的作用:实现继承,减少重复代码。
✅ __proto__ :对象的原型指向父对象。
✅ 查找规则:先找自身,再沿原型链向上查找,直到 null。
✅ 类继承:class 只是 prototype 继承的语法糖,本质仍是原型链。
如果你还有疑问,可以问我!😊