当前位置:首页 > JavaScript

实现extend js

2026-04-07 01:29:12JavaScript

在 JavaScript 中实现继承

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

原型链继承

通过将子类的原型指向父类的实例来实现继承:

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"

构造函数继承

在子类构造函数中调用父类构造函数:

实现extend js

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;

ES6 class 继承

使用 ES6 的 class 和 extends 关键字:

实现extend js

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

  sayName() {
    console.log(this.name);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name);
    this.age = age;
  }
}

Object.create() 实现继承

使用 Object.create() 创建原型对象:

const parent = {
  sayHello() {
    console.log('Hello');
  }
};

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

inheritPrototype(Child, Parent);

选择哪种继承方式取决于具体需求,ES6 的 class 语法是最简洁现代的实现方式。

标签: extendjs
分享给朋友:

相关文章

js实现轮播

js实现轮播

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

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数:…

js实现菜单

js实现菜单

实现基本HTML结构 使用HTML创建菜单的基本框架,通常包含<ul>和<li>元素。示例结构如下: <ul id="menu"> <li><…

js实现显示隐藏

js实现显示隐藏

显示隐藏的实现方法 在JavaScript中,实现元素的显示和隐藏可以通过多种方式完成。以下是几种常见的方法: 修改CSS的display属性 通过改变元素的display属性可以在none(隐藏)…

js实现定位

js实现定位

使用Geolocation API获取当前位置 在JavaScript中,可以通过浏览器内置的Geolocation API获取用户的地理位置信息。该API需要用户授权才能访问位置数据。 if (n…

js 实现验证码

js 实现验证码

实现验证码的 JavaScript 方法 生成随机验证码 验证码通常由随机字符(数字、字母或混合)组成。以下代码生成一个 6 位随机验证码(数字和字母混合): function generateCa…