JavaScript 原型链继承的六种常见方式解析

ChatGPT4o 使用 ChatGPT 4o 回答

问题:

js 原型链 继承 方式

回答:

在 JavaScript 中,原型链继承是实现对象继承的一种方式。通过原型链继承,一个对象可以继承另一个对象的属性和方法。以下是几种常见的原型链继承方式:

1. 原型链继承

这是最基本的继承方式,通过将子类的原型指向父类的实例来实现。

function Parent() {
    this.name = 'Parent';
}

Parent.prototype.sayHello = function() {
    console.log('Hello from Parent');
};

function Child() {
    this.age = 18;
}

// 关键点:将子类的原型指向父类的实例
Child.prototype = new Parent();
Child.prototype.constructor = Child;

const child = new Child();
console.log(child.name); // Parent
child.sayHello(); // Hello from Parent

2. 借用构造函数(经典继承)

通过在子类构造函数中调用父类构造函数来实现继承。

function Parent(name) {
    this.name = name;
}

function Child(name, age) {
    Parent.call(this, name); // 关键点:调用父类构造函数
    this.age = age;
}

const child = new Child('Child', 18);
console.log(child.name); // Child
console.log(child.age); // 18

3. 组合继承

组合继承结合了原型链继承和借用构造函数的优点,既能继承父类的属性,又能继承父类的原型方法。

function Parent(name) {
    this.name = name;
}

Parent.prototype.sayHello = function() {
    console.log('Hello from Parent');
};

function Child(name, age) {
    Parent.call(this, name); // 借用构造函数
    this.age = age;
}

// 原型链继承
Child.prototype = new Parent();
Child.prototype.constructor = Child;

const child = new Child('Child', 18);
console.log(child.name); // Child
console.log(child.age); // 18
child.sayHello(); // Hello from Parent

4. 原型式继承

通过 Object.create 方法实现继承。

const parent = {
    name: 'Parent',
    sayHello: function() {
        console.log('Hello from Parent');
    }
};

const child = Object.create(parent);
child.age = 18;

console.log(child.name); // Parent
child.sayHello(); // Hello from Parent
console.log(child.age); // 18

5. 寄生式继承

在原型式继承的基础上,增强对象。

function createChild(original) {
    const clone = Object.create(original);
    clone.sayHi = function() {
        console.log('Hi from Child');
    };
    return clone;
}

const parent = {
    name: 'Parent',
    sayHello: function() {
        console.log('Hello from Parent');
    }
};

const child = createChild(parent);
child.sayHi(); // Hi from Child
child.sayHello(); // Hello from Parent

6. 寄生组合式继承

这是最推荐的继承方式,避免了组合继承中多次调用父类构造函数的问题。

function Parent(name) {
    this.name = name;
}

Parent.prototype.sayHello = function() {
    console.log('Hello from Parent');
};

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('Child', 18);
console.log(child.name); // Child
console.log(child.age); // 18
child.sayHello(); // Hello from Parent

这些是 JavaScript 中常见的原型链继承方式,每种方式都有其适用的场景和优缺点。选择合适的继承方式可以帮助你更好地组织和