原型链知识
在JavaScript中,每个对象都有一个指向它的原型(prototype)的内部链接。当试图访问一个对象的属性时,如果这个对象内部不存在这个属性,那么JavaScript就会在对象的原型(也就是它的__proto__
属性指向的对象)上寻找这个属性,如果还没有找到,就会继续在该原型的原型上寻找,依此类推,直到找到属性或者达到原型链的末尾(通常是Object.prototype
,其原型是null
)。这种通过原型链实现继承和属性查找的机制,是JavaScript中实现面向对象编程的重要组成部分。
实例:原型链的演示
以下是一个简单的例子,演示了如何通过原型链访问和继承属性:
// 定义一个构造函数Person
function Person(name) {
this.name = name;
}
// 在Person的原型上添加一个方法sayHello
Person.prototype.sayHello = function() {
console.log('Hello, my name is ' + this.name);
};
// 定义一个构造函数Student,继承自Person
function Student(name, grade) {
Person.call(this, name); // 调用Person构造函数初始化Student实例的name属性
this.grade = grade; // 定义Student实例特有的grade属性
}
// 设置Student的原型为Person的一个实例,实现继承
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student; // 修复构造函数指向
// 在Student的原型上添加一个方法study
Student.prototype.study = function() {
console.log('I am studying in grade ' + this.grade);
};
// 创建一个Student实例并测试
var tom = new Student('Tom', 3);
tom.sayHello(); // 访问继承来的方法:Hello, my name is Tom
tom.study(); // 访问自己的方法:I am studying in grade 3
在这个例子中,Student
构造函数通过Person.call(this, name)
语句实现了对Person
构造函数的借用,使得Student
的实例能够拥有name
属性。然后,通过设置Student.prototype
为Person.prototype
的一个新对象(使用Object.create()
创建),实现了原型链上的继承。这样,Student
的实例不仅能够访问自己的study()
方法,还能访问从Person
原型上继承来的sayHello()
方法。