当前位置:首页 > JavaScript

js实现extends

2026-03-14 01:56:42JavaScript

实现继承的方式

在JavaScript中,继承可以通过多种方式实现,以下是常见的几种方法:

原型链继承 通过将子类的原型指向父类的实例来实现继承。这种方法简单,但存在引用类型共享的问题。

js实现extends

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

function Child() {}
Child.prototype = new Parent();

const child = new Child();
child.sayName(); // 'parent'

构造函数继承 在子类构造函数中调用父类构造函数,使用callapply方法。这种方法解决了引用类型共享的问题,但无法继承父类原型上的方法。

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

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

const child = new Child('child');
console.log(child.name); // 'child'
child.sayName(); // Error: child.sayName is not a function

组合继承 结合原型链继承和构造函数继承,既能继承父类实例属性,又能继承父类原型上的方法。但会调用两次父类构造函数。

js实现extends

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

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

const child = new Child('child');
child.sayName(); // 'child'

寄生组合继承 通过Object.create来优化组合继承,避免重复调用父类构造函数。这是目前最理想的继承方式。

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

function Child(name) {
    Parent.call(this, name);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

const child = new Child('child');
child.sayName(); // 'child'

ES6类继承 使用classextends关键字实现继承,语法更简洁,底层仍然是基于原型链的继承。

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

class Child extends Parent {
    constructor(name) {
        super(name);
    }
}

const child = new Child('child');
child.sayName(); // 'child'

注意事项

  • 原型链继承会导致引用类型属性被所有实例共享。
  • 构造函数继承无法继承父类原型上的方法。
  • 组合继承会调用两次父类构造函数,可能影响性能。
  • 寄生组合继承是最优解,避免了组合继承的缺点。
  • ES6类继承语法更现代,推荐在新项目中使用。

标签: jsextends
分享给朋友:

相关文章

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Pro…

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含inpu…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js实现图

js实现图

JavaScript 实现图的常用方法 在 JavaScript 中,图(Graph)可以通过多种方式实现,常见的包括邻接表(Adjacency List)和邻接矩阵(Adjacency Matrix…