当前位置:首页 > JavaScript

js实现继承

2026-04-03 17:58:40JavaScript

原型链继承

利用原型链实现继承的基本思想是通过原型将一个引用类型继承另一个引用类型的属性和方法。构造函数、原型和实例之间的关系可以用原型链来表示。

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

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

function Child() {
  this.childName = 'child';
}

Child.prototype = new Parent();

const child = new Child();
child.sayName(); // 输出: parent

构造函数继承

在子类型构造函数的内部调用超类型构造函数,通过使用call()或apply()方法可以在新创建的对象上执行构造函数。

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

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

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

组合继承

组合继承结合了原型链继承和构造函数继承的优点,避免了单独使用它们时的缺陷。通过原型链实现对原型属性和方法的继承,通过借用构造函数实现对实例属性的继承。

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

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

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

Child.prototype = new Parent();
Child.prototype.constructor = Child;

const child = new Child('child', 10);
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

寄生式继承

创建一个仅用于封装继承过程的函数,该函数在内部以某种方式来增强对象,最后返回对象。

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

const parent = {
  name: 'parent'
};

const child = createAnother(parent);
child.sayHi(); // 输出: hi

寄生组合式继承

通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。基本思路是不必为了指定子类型的原型而调用超类型的构造函数。

js实现继承

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, age) {
  Parent.call(this, name);
  this.age = age;
}

inheritPrototype(Child, Parent);

const child = new Child('child', 10);
child.sayName(); // 输出: child

标签: js
分享给朋友:

相关文章

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js jquery

js jquery

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

js实现授权

js实现授权

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

js验证码的实现

js验证码的实现

验证码的基本实现原理 验证码(CAPTCHA)的核心目标是区分人类用户和自动化程序。JavaScript可用于生成或验证客户端验证码,但需注意纯前端验证可能被绕过,通常需结合后端验证。 纯前端验证码…