实现一种js原型继承
原型继承的基本概念
在JavaScript中,原型继承是通过原型链实现的。每个对象都有一个原型(__proto__),指向另一个对象。当访问对象的属性或方法时,如果对象本身没有,会沿着原型链向上查找。
构造函数模式
通过构造函数和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; // 修正构造函数指向
Child.prototype.sayAge = function() {
console.log(this.age);
};
const child = new Child('Alice', 10);
child.sayName(); // "Alice"
child.sayAge(); // 10
Object.create()实现纯净继承
直接基于已有对象创建新对象,无需构造函数。
const parent = {
name: 'Parent',
sayName() {
console.log(this.name);
}
};
const child = Object.create(parent);
child.name = 'Child';
child.sayName(); // "Child"
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;
}
sayAge() {
console.log(this.age);
}
}
const child = new Child('Bob', 12);
child.sayName(); // "Bob"
child.sayAge(); // 12
注意事项
- 使用
Object.create()时需手动修正constructor属性。 - ES6
class本质仍是原型继承的语法糖,但更清晰易读。 - 避免直接修改
__proto__属性,优先使用标准方法。







