万字详解 JS 继承,属性和方法怎么共享?用原型链!
2024-01-01 16:00:53
一、问题引出
在 JS 中,我们经常会遇到这样的场景:多个对象需要共享相同的属性和方法。比如,我们有一个 Person
构造函数,它定义了所有人的共有属性和方法,如姓名、年龄和说话。现在,我们想创建一个 Student
构造函数,它继承了 Person
构造函数的所有属性和方法,并添加了一些新的属性和方法,如学号和学习。
如何实现这种继承呢?
二、原型链的引入
为了解决这个问题,JS 引入了原型链的概念。每个 JS 对象都有一个内部属性 __proto__
,指向它的原型对象。原型对象也是一个 JS 对象,它拥有自己的属性和方法。当一个对象访问一个不存在的属性或方法时,JS 会沿着原型链向上查找,直到找到该属性或方法。
function Person(name, age) {
this.name = name;
this.age = age;
this.speak = function() {
console.log(`My name is ${this.name}, I am ${this.age} years old.`);
};
}
function Student(name, age, school) {
Person.call(this, name, age); // 调用父类构造函数
this.school = school;
this.study = function() {
console.log(`I am studying at ${this.school}.`);
};
}
// 设置 Student 的原型对象为 Person.prototype
Student.prototype = new Person();
// 创建一个 Student 对象
const student = new Student('John', 20, 'Harvard');
// 访问 Student 对象的属性和方法
console.log(student.name); // John
console.log(student.age); // 20
student.speak(); // My name is John, I am 20 years old.
student.study(); // I am studying at Harvard.
在上面的示例中,我们创建了一个 Person
构造函数和一个 Student
构造函数。Student
构造函数继承了 Person
构造函数的所有属性和方法。这是通过将 Student.prototype
设置为 new Person()
来实现的。
三、原型链的查找过程
当我们访问 student
对象的属性或方法时,JS 会沿着原型链向上查找,直到找到该属性或方法。例如,当我们访问 student.name
时,JS 会首先在 student
对象中查找 name
属性。如果没有找到,JS 会沿着原型链向上查找,直到找到 Person.prototype
对象。在 Person.prototype
对象中,JS 会找到 name
属性,并将其值返回给 student
对象。
四、原型链的意义
原型链是 JS 继承机制的核心。它允许对象共享属性和方法,从而实现代码的重用。原型链还使 JS 具有了面向对象编程的能力,使我们可以创建出更复杂和可维护的程序。
五、总结
原型链是 JS 中一个非常重要的概念。它使 JS 对象能够共享属性和方法,从而实现代码的重用。原型链还使 JS 具有了面向对象编程的能力,使我们可以创建出更复杂和可维护的程序。
如果你想深入理解 JS 继承机制,那么你必须掌握原型链的概念。