js prototype 实现
理解 JavaScript 原型链
JavaScript 是一种基于原型的语言,每个对象都有一个原型对象,对象从原型继承属性和方法。原型链是 JavaScript 实现继承的核心机制。
创建对象并使用原型
通过构造函数创建对象时,新对象的原型会指向构造函数的 prototype 属性。例如:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Alice');
person1.greet(); // 输出: Hello, my name is Alice
原型链继承
通过将子类的原型指向父类的实例,可以实现继承:

function Student(name, grade) {
Person.call(this, name); // 调用父类构造函数
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', 5);
student1.greet(); // 输出: Hello, my name is Bob
student1.study(); // 输出: Bob is studying in grade 5
使用 Object.setPrototypeOf
ES6 提供了 Object.setPrototypeOf 方法直接设置对象的原型:
const animal = {
eat() {
console.log(`${this.name} eats`);
}
};
const dog = {
name: 'Rex',
bark() {
console.log(`${this.name} barks`);
}
};
Object.setPrototypeOf(dog, animal);
dog.eat(); // 输出: Rex eats
dog.bark(); // 输出: Rex barks
原型链的终点
所有对象的原型链最终指向 Object.prototype,而 Object.prototype 的原型是 null:

console.log(Object.getPrototypeOf(Object.prototype)); // 输出: null
检查原型关系
使用 instanceof 运算符可以检查对象是否在原型链上:
console.log(student1 instanceof Student); // true
console.log(student1 instanceof Person); // true
console.log(student1 instanceof Object); // true
避免直接修改内置原型
虽然可以修改内置对象的原型(如 Array.prototype),但这通常是不推荐的,因为它可能导致不可预测的行为:
Array.prototype.customMethod = function() {
console.log('Custom array method');
};
const arr = [1, 2, 3];
arr.customMethod(); // 输出: Custom array method
性能考虑
过长的原型链会影响性能,因为查找属性时需要遍历整个链。尽量保持原型链简洁。






