当前位置:首页 > 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实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…

js实现乘

js实现乘

JavaScript 实现乘法运算 在 JavaScript 中实现乘法运算可以通过多种方式完成,包括基本运算符、函数封装以及高级算法(如大数乘法)。以下是几种常见方法: 使用基本乘法运算符 Jav…

js实现瀑布流

js实现瀑布流

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

js实现交换

js实现交换

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

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js实现上传文件

js实现上传文件

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。 <input type="file"…