js prototype 实现
原型(Prototype)的概念
在JavaScript中,每个函数都有一个特殊的属性叫做prototype。这个属性指向一个对象,该对象包含了可以由特定类型的所有实例共享的属性和方法。原型的主要作用是实现继承和共享属性。
原型的基本实现
定义一个构造函数,并通过原型添加方法:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
const person1 = new Person('Alice', 25);
person1.greet(); // 输出: Hello, my name is Alice and I am 25 years old.
原型链继承
通过原型链实现继承,子类的原型指向父类的实例:

function Student(name, age, grade) {
Person.call(this, name, age); // 调用父类构造函数
this.grade = grade;
}
Student.prototype = Object.create(Person.prototype); // 继承父类原型
Student.prototype.constructor = Student; // 修复构造函数指向
Student.prototype.study = function() {
console.log(`${this.name} is studying in grade ${this.grade}.`);
};
const student1 = new Student('Bob', 16, 10);
student1.greet(); // 输出: Hello, my name is Bob and I am 16 years old.
student1.study(); // 输出: Bob is studying in grade 10.
原型方法的重写
子类可以重写父类的方法:
Student.prototype.greet = function() {
console.log(`Hi, I'm ${this.name}, a student in grade ${this.grade}.`);
};
student1.greet(); // 输出: Hi, I'm Bob, a student in grade 10.
静态方法与实例方法
静态方法是直接定义在构造函数上的方法,实例方法是定义在原型上的方法:

Person.staticMethod = function() {
console.log('This is a static method.');
};
Person.staticMethod(); // 输出: This is a static method.
原型链的查找机制
当访问一个对象的属性或方法时,JavaScript会先在对象自身查找,如果没有找到,会沿着原型链向上查找,直到找到或到达原型链的顶端(null)。
console.log(student1.hasOwnProperty('name')); // true
console.log(student1.hasOwnProperty('greet')); // false
使用Object.getPrototypeOf和__proto__
获取对象的原型:
console.log(Object.getPrototypeOf(student1) === Student.prototype); // true
console.log(student1.__proto__ === Student.prototype); // true
原型与性能
共享方法通过原型实现可以减少内存占用,因为所有实例共享同一个方法,而不是每个实例都创建一份方法的副本。






