实现一个js原型继承
原型继承的实现方法
在JavaScript中,原型继承可以通过多种方式实现。以下是几种常见的实现方法:
构造函数继承
使用构造函数和prototype属性实现原型继承:

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('Alice', 10);
child.sayName(); // 输出: Alice
ES6类继承
使用ES6的class和extends关键字实现继承:

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('Bob', 12);
child.sayName(); // 输出: Bob
Object.create方法
直接使用Object.create()实现原型继承:
const parent = {
name: 'Parent',
sayName() {
console.log(this.name);
}
};
const child = Object.create(parent);
child.name = 'Child';
child.sayName(); // 输出: Child
混合继承
结合构造函数和原型链的混合继承方式:
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;
}
// 使用Object.create避免重复调用父类构造函数
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() {
console.log(this.age);
};
const child = new Child('Charlie', 8);
child.sayName(); // 输出: Charlie
child.sayAge(); // 输出: 8
原型继承的注意事项
- 修改子类原型时,注意保持正确的
constructor引用 - 使用
Object.create()可以避免直接修改父类原型 - ES6类语法是语法糖,底层仍然基于原型继承
- 深度继承链可能导致性能问题






