在 JavaScript 中,实现继承有多种方式。以下是其中几种常见的方式:
1:原型链继承:
原型链继承是通过将一个对象的实例作为另一个对象的原型来实现继承关系。子对象通过原型链可以访问父对象的属性和方法。
示例:
function Parent() {
this.name = "Parent";
}
Parent.prototype.sayHello = function() {
console.log("Hello, I'm " + this.name);
};
function Child() {
this.name = "Child";
}
Child.prototype = new Parent();
const child = new Child();
child.sayHello(); // 输出: Hello, I'm Child
2:构造函数继承:
构造函数继承是通过在子对象的构造函数中调用父对象的构造函数来实现继承。这种方式可以实现属性的继承,但无法继承父对象原型上的方法。
示例:
function Parent() {
this.name = "Parent";
}
function Child() {
Parent.call(this);
this.name = "Child";
}
const child = new Child();
console.log(child.name); // 输出: Child
3:组合继承:
组合继承是将原型链继承和构造函数继承结合起来的一种方式。通过调用父对象的构造函数实现属性的继承,并将子对象的原型设置为父对象的实