举例说明js如何实现继承?

在JavaScript中,继承是面向对象编程中的一个核心概念,它允许一个类(称为子类或派生类)继承另一个类(称为父类或基类)的属性和方法。虽然JavaScript不是一种严格的基于类的语言,但它提供了几种方式来实现继承。

以下是几种在JavaScript中实现继承的常用方法:

1. 原型链继承

原型链是JavaScript中实现继承的主要方法。在这种方法中,子类的原型被设置为父类的一个实例。

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

Parent.prototype.sayName = function() {
    console.log(this.name);
};

function Child() {
    this.type = 'Child';
}

// 实现继承
Child.prototype = new Parent();

var child = new Child();
child.sayName(); // 输出: Parent

2. 借用构造函数继承

在这种方法中,我们在子类的构造函数内部调用(借用)父类的构造函数。

function Parent() {
    this.name = 'Parent';
    this.colors = ['red', 'blue', 'green'];
}

function Child() {
    Parent.call(this); // 借用构造函数
    this.type = 'Child';
}

var child1 = new Child();
child1.colors.push('black');
console.log(child1.colors); // 输出: ["red", "blue", "green", "black"]

var child2 = new Child();
console.log(child2.colors); // 输出: ["red", "blue", "green"]

3. 组合继承(原型链 + 借用构造函数)

组合继承结合了原型链和借用构造函数的优点,是最常用的继承模式。

function Parent() {
    this.name = 'Parent';
    this.colors = ['red', 'blue', 'green'];
}

Parent.prototype.sayName = function() {
    console.log(this.name);
};

function Child() {
    Parent.call(this); // 借用构造函数
    this.type = 'Child';
}

Child.prototype = Object.create(Parent.prototype); // 设置原型链实现继承
Child.prototype.constructor = Child; // 修复构造函数引用

var child1 = new Child();
child1.colors.push('black');
console.log(child1.colors); // 输出: ["red", "blue", "green", "black"]
child1.sayName(); // 输出: Parent

var child2 = new Child();
console.log(child2.colors); // 输出: ["red", "blue", "green"]

4. ES6类继承

在ES6中,我们可以使用classextends关键字来更简洁地实现继承。

class Parent {
    constructor() {
        this.name = 'Parent';
    }
    sayName() {
        console.log(this.name);
    }
}

class Child extends Parent {
    constructor() {
        super(); // 调用父类的构造函数
        this.type = 'Child';
    }
}

const child = new Child();
child.sayName(); // 输出: Parent
posted @ 2025-01-15 09:35  王铁柱6  阅读(2)  评论(0编辑  收藏  举报