js原型实现
原型的概念
在JavaScript中,每个对象都有一个原型(prototype),原型本身也是一个对象。原型用于实现继承和共享属性、方法。通过原型链,对象可以访问其原型上的属性和方法。
原型的基本使用
通过构造函数创建对象时,新对象的原型会指向构造函数的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
原型链的查找机制
当访问对象的属性或方法时,JavaScript引擎会先在对象自身查找。如果找不到,会沿着原型链向上查找,直到找到或到达原型链的顶端(null)。
console.log(person1.hasOwnProperty('name')); // true
console.log(person1.hasOwnProperty('greet')); // false
修改原型
可以直接修改构造函数的prototype属性来影响所有实例。需要注意的是,修改原型会影响所有已创建和未来创建的实例。
Person.prototype.farewell = function() {
console.log(`${this.name} says goodbye!`);
};
person1.farewell(); // 输出: Alice says goodbye!
原型继承
通过将子类的原型设置为父类的实例,可以实现原型继承。
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.create方法
Object.create方法可以创建一个新对象,并指定其原型。
const animal = {
makeSound: function() {
console.log(this.sound);
}
};
const dog = Object.create(animal);
dog.sound = 'Woof!';
dog.makeSound(); // 输出: Woof!
原型与性能
频繁修改原型可能会影响性能,尤其是在大型应用中。建议在初始化阶段完成原型的修改,避免运行时动态修改。
检查原型关系
可以使用instanceof运算符或Object.getPrototypeOf方法来检查对象的原型关系。

console.log(student1 instanceof Person); // true
console.log(Object.getPrototypeOf(student1) === Student.prototype); // true






