js原型实现
原型的基本概念
在JavaScript中,每个对象都有一个原型(prototype),原型本身也是一个对象。通过原型,对象可以继承其他对象的属性和方法。原型链是JavaScript实现继承的主要机制。
原型链的实现
每个构造函数都有一个prototype属性,指向一个对象,这个对象就是通过该构造函数创建的实例的原型。实例通过proto属性访问其原型。
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
const person1 = new Person('Alice');
person1.sayHello(); // 输出: Hello, Alice
原型继承
通过将一个构造函数的prototype指向另一个构造函数的实例,可以实现原型继承。这样,子类的实例可以访问父类的属性和方法。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log('My name is ' + this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() {
console.log('I am ' + this.age + ' years old');
};
const child = new Child('Bob', 10);
child.sayName(); // 输出: My name is Bob
child.sayAge(); // 输出: I am 10 years old
修改原型
可以通过直接修改prototype对象来动态添加或修改方法。所有实例都会立即继承这些变化。
function Car() {}
const car1 = new Car();
Car.prototype.drive = function() {
console.log('Driving...');
};
car1.drive(); // 输出: Driving...
原型链的终点
所有对象的原型链最终都会指向Object.prototype,而Object.prototype的原型是null。
console.log(Object.prototype.__proto__); // 输出: null
检查原型关系
可以使用instanceof运算符检查对象是否在某个构造函数的原型链上,或者使用isPrototypeOf方法检查一个对象是否是另一个对象的原型。

console.log(child instanceof Parent); // 输出: true
console.log(Parent.prototype.isPrototypeOf(child)); // 输出: true






