当前位置:首页 > JavaScript

js实现继承方式

2026-03-01 01:22:42JavaScript

原型链继承

通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。

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'

构造函数继承

在子类构造函数中调用父类构造函数,使用call或apply方法改变this指向。

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

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

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

组合继承

结合原型链继承和构造函数继承,既继承原型上的方法,又继承实例属性。

js实现继承方式

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()方法创建一个新对象,使用现有对象作为新对象的原型。

const parent = {
  name: 'parent',
  sayName: function() {
    console.log(this.name);
  }
};

const child = Object.create(parent);
child.name = 'child';
child.sayName(); // 'child'

寄生式继承

在原型式继承的基础上增强对象,返回一个增强后的对象。

js实现继承方式

function createAnother(original) {
  const clone = Object.create(original);
  clone.sayHello = function() {
    console.log('hello');
  };
  return clone;
}

const parent = {
  name: 'parent'
};

const child = createAnother(parent);
child.sayHello(); // 'hello'

寄生组合式继承

通过借用构造函数继承属性,通过原型链混成形式继承方法。

function inheritPrototype(child, parent) {
  const prototype = Object.create(parent.prototype);
  prototype.constructor = child;
  child.prototype = prototype;
}

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

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

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

ES6类继承

使用class和extends关键字实现继承,语法更简洁。

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'

标签: 方式js
分享给朋友:

相关文章

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval…

jquery js

jquery js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够更高…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

js实现授权

js实现授权

授权流程设计 授权流程通常涉及前端与后端的交互,常见方案包括OAuth2.0、JWT等。以JWT为例的典型流程: 用户提交凭证(如用户名密码)到认证服务 服务端验证通过后生成包含用户信息的JWT令…

js实现交换

js实现交换

交换变量的方法 在JavaScript中,交换两个变量的值有多种方法。以下是常见的几种实现方式: 使用临时变量 通过引入一个临时变量来存储其中一个变量的值,实现交换: let a = 1;…