js 实现原型
原型的基本概念
在JavaScript中,每个函数都有一个prototype属性,指向一个对象。这个对象是构造函数的原型,所有通过该构造函数创建的实例都可以共享原型上的属性和方法。
原型链的机制
当访问一个对象的属性或方法时,JavaScript会先在对象自身查找。如果找不到,会沿着原型链向上查找,直到找到或到达原型链的末端(null)。
实现原型继承
构造函数与原型
定义一个构造函数时,可以通过prototype属性为其添加共享的属性和方法。

function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Alice');
person1.sayHello(); // 输出: Hello, my name is Alice
原型链继承
通过将子类的原型设置为父类的实例,可以实现原型链继承。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const child = new Child('Bob', 10);
child.sayName(); // 输出: Bob
ES6的class语法
ES6引入了class语法,简化了原型继承的实现。

class Parent {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
const child = new Child('Charlie', 12);
child.sayName(); // 输出: Charlie
原型相关方法
Object.create()
创建一个新对象,使用现有对象作为新对象的原型。
const parent = {
greet() {
console.log('Hello from parent');
}
};
const child = Object.create(parent);
child.greet(); // 输出: Hello from parent
Object.getPrototypeOf()
获取指定对象的原型。
const obj = {};
console.log(Object.getPrototypeOf(obj) === Object.prototype); // 输出: true
Object.setPrototypeOf()
设置指定对象的原型。
const obj1 = { a: 1 };
const obj2 = { b: 2 };
Object.setPrototypeOf(obj1, obj2);
console.log(obj1.b); // 输出: 2
注意事项
- 避免直接修改
__proto__属性,使用Object.setPrototypeOf()更安全。 - 原型链过长会影响性能,需谨慎设计继承层次。
- 在ES6中,优先使用
class和extends实现继承,代码更清晰易读。






