实现一个js原型继承
原型继承的基本概念
在JavaScript中,每个对象都有一个内部属性[[Prototype]],通常通过__proto__或Object.getPrototypeOf()访问。原型继承允许对象从另一个对象继承属性和方法。
构造函数方式实现原型继承
通过构造函数和prototype属性实现继承:
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log(`Hello, ${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.sayHello(); // 输出: Hello, Alice
ES6 class语法实现继承
使用ES6的class和extends关键字更简洁:
class Parent {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}`);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
const child = new Child('Bob', 12);
child.sayHello(); // 输出: Hello, Bob
Object.create实现纯对象继承
直接通过对象之间的继承:
const parent = {
greet() {
console.log(`Hi, ${this.name}`);
}
};
const child = Object.create(parent);
child.name = 'Charlie';
child.greet(); // 输出: Hi, Charlie
原型链的注意事项
修改子类原型时需保持原型链完整:
Child.prototype.newMethod = function() {
console.log(`Age: ${this.age}`);
};
避免直接修改__proto__属性,这会带来性能问题。优先使用Object.create()或class语法。







