在JavaScript中,每个函数都有一个特殊的属性——prototype(原型对象)。这是JavaScript实现继承和共享属性的核心机制。
什么是Prototype?
当我们创建一个新函数时,JavaScript会自动为该函数添加一个prototype属性,这个属性指向一个空对象(即原型对象)。这个对象包含一个constructor属性,指回原函数。
function Person(name) {
this.name = name;
}
// 为Person的原型添加方法
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
const john = new Person('John');
console.log(john.greet()); // "Hello, I'm John"
原型链如何工作?
当我们访问对象的属性或方法时,JavaScript首先在对象自身查找,如果找不到,就会沿着原型链向上查找,直到找到该属性或到达链的末端(null)。
console.log(john.hasOwnProperty('name')); // true
console.log(john.hasOwnProperty('greet')); // false
console.log(john.__proto__.hasOwnProperty('greet')); // true
实现继承
通过设置构造函数的prototype,我们可以实现继承:
function Student(name, major) {
Person.call(this, name);
this.major = major;
}
// 设置原型链继承
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.study = function() {
return `${this.name} is studying ${this.major}`;
};
const alice = new Student('Alice', 'Computer Science');
console.log(alice.greet()); // 继承自Person
console.log(alice.study()); //自己的方法
理解prototype是掌握JavaScript面向对象编程的关键,它使得对象可以共享方法,减少内存消耗,同时实现了灵活的原型链继承机制。
1251

被折叠的 条评论
为什么被折叠?



