js 继承有哪些方式

JavaScript 中实现继承的方式有多种,每种方式都有其特点和适用场景。以下是一些常见的继承模式:

1. 原型链继承

原型链继承是最基础的继承方式,它通过将子类的原型对象指向父类的一个实例来实现属性和方法的共享。

示例代码:
javascript 复制代码
function Parent() {
    this.name = 'parent';
}

Parent.prototype.getName = function() {
    return this.name;
};

function Child() {
    // 无需额外操作
}

Child.prototype = new Parent(); // 关键点:让Child的prototype指向Parent的一个实例
Child.prototype.constructor = Child;

var child = new Child();
console.log(child.getName()); // 输出: parent

2. 构造函数继承

构造函数继承涉及到在子类的构造函数内部调用父类的构造函数,并且改变父类构造函数中的this指向子类实例。

示例代码:
javascript 复制代码
function Parent() {
    this.name = 'parent';
}

function Child() {
    Parent.call(this); // 关键点:在Child构造函数中调用Parent,并绑定this
}

var child = new Child();
console.log(child.name); // 输出: parent

3. 组合继承(经典继承)

组合继承结合了原型链继承和构造函数继承的优点,通过在子类的构造函数中调用父类的构造函数,并且让子类的原型指向父类的原型的一个实例来实现继承。

示例代码:
javascript 复制代码
function Parent(name) {
    this.name = name;
}

Parent.prototype.getName = function() {
    return this.name;
};

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

Child.prototype = new Parent(); // 继承Parent的原型方法
Child.prototype.constructor = Child;

var child = new Child('parent', 10);
console.log(child.getName()); // 输出: parent
console.log(child.age);       // 输出: 10

4. 寄生组合继承

寄生组合继承改进了组合继承中的一个问题:每次创建子类实例时,父类构造函数都会被调用两次。它使用一个中间函数来继承父类的原型属性。

示例代码:
javascript 复制代码
function inheritPrototype(subType, superType) {
    var prototype = Object.create(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
}

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

Parent.prototype.getName = function() {
    return this.name;
};

function Child(name, age) {
    Parent.call(this, name);
    this.age = age;
}

inheritPrototype(Child, Parent);

var child = new Child('parent', 10);
console.log(child.getName()); // 输出: parent
console.log(child.age);       // 输出: 10

5. ES6 类继承

ES6 引入了类的概念

相关推荐
运维@小兵5 分钟前
vue配置子路由,实现点击左侧菜单,内容区域显示不同的内容
前端·javascript·vue.js
海绵宝宝贾克斯儿39 分钟前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔011239 分钟前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式
GISer_Jing1 小时前
[前端高频]数组转树、数组扁平化、深拷贝、JSON.stringify&JSON.parse等手撕
前端·javascript·json
isyangli_blog1 小时前
(1-4)Java Object类、Final、注解、设计模式、抽象类、接口、内部类
java·开发语言
三块钱07941 小时前
【原创】基于视觉大模型gemma-3-4b实现短视频自动识别内容并生成解说文案
开发语言·python·音视频
易只轻松熊1 小时前
C++(20): 文件输入输出库 —— <fstream>
开发语言·c++·算法
古拉拉明亮之神1 小时前
Spark处理过程-转换算子
javascript·ajax·spark
芯眼1 小时前
ALIENTEK精英STM32F103开发板 实验0测试程序详解
开发语言·c++·stm32·单片机·嵌入式硬件·社交电子
青出于兰2 小时前
C语言| 指针变量的定义
c语言·开发语言