迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中实现单体类

作者:迹忆客 最近更新:2024/03/22 浏览次数:

在今天的文章中,我们将学习如何使用最简单的方式在 JavaScript 中实现单例类。


JavaScript 中的单例实现

在 Java 等编程语言中,一个对象可以有多个实例。但是当我们只想限制一个对象的单个实例时,就会出现单例模式。

此模式将特定对象的实例数限制为在任何给定时间点只有一个。这个单一实例的名称是一个单例。

当从中央位置协调系统级操作时,此概念很有用。最好的例子之一是数据库连接池。

数据库连接对任何应用程序都很重要,池管理整个应用程序的所有数据库连接的创建、销毁和持续时间,确保没有连接丢失。

让我们举个例子。

const SingletonFunction = (function() {
  let instance;

  function createInstance() {
    return new Object('Instance of SingletonFunction');
  }

  return {
    getInstance: function() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

function TestSingletonFunction() {
  const instance1 = SingletonFunction.getInstance();
  const instance2 = SingletonFunction.getInstance();
  console.log('Both instances are the same? ' + (instance1 === instance2));
}
TestSingletonFunction()

在上面的示例中,getInstance 方法充当 Singleton 看门人。它返回对象的唯一实例,同时维护对它的私有引用,外部世界无法访问。

getInstance 方法说明了另一种称为 Lazy Load 的设计模式。延迟加载检查是否已经创建了实例;否则,它将创建一个并将其存储以供将来参考。

所有后续调用都将收到存档的实例。延迟加载是一种节省内存和 CPU 的技术,它仅在必要时创建对象。

当你创建单例方法的两个实例时,这两个实例在数据类型和值方面是相同的。当你在任何浏览器中运行上述代码时,你会看到两个实例都是同一个实例。

输出:

"Both instances are the same? true"

JavaScript 中单例的优点

全局变量是 JavaScript 的重要组成部分,但单例减少了对全局变量的需求。当只需要一个实例时,其他几个模型,例如 FactoryPrototypeFaçade,通常作为 Singleton 实现。

这个对象被实现为一个即时的、匿名的函数。该函数通过用括号括起来立即执行,然后再加上两个括号。

因为没有名字,所以叫匿名。

Singleton 是常见 JavaScript 模式的一种表现形式:Module.Module 模式是所有主要 JavaScript 库和框架(jQuery、Backbone、Ember 等)的基础。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便