在 JavaScript 中实现单例的最简单/最干净的方法 [英] Simplest/cleanest way to implement a singleton in JavaScript

查看:42
本文介绍了在 JavaScript 中实现单例的最简单/最干净的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中实现单例模式的最简单/最干净的方法是什么?

What is the simplest/cleanest way to implement the singleton pattern in JavaScript?

推荐答案

ES6 正确的做法是:

class MyClass {
  constructor() {
    if (MyClass._instance) {
      throw new Error("Singleton classes can't be instantiated more than once.")
    }
    MyClass._instance = this;

    // ... Your rest of the constructor code goes after this
  }
}

var instanceOne = new MyClass() // Executes succesfully
var instanceTwo = new MyClass() // Throws error

或者,如果您不想在创建第二个实例时抛出错误,您可以只返回最后一个实例,如下所示:

Or, if you don't want an error to be thrown on the second instance creation, you can just return the last instance, like so:

class MyClass {
  constructor() {
    if (MyClass._instance) {
      return MyClass._instance
    }
    MyClass._instance = this;

    // ... Your rest of the constructor code goes after this
  }
}

var instanceOne = new MyClass()
var instanceTwo = new MyClass()

console.log(instanceOne === instanceTwo) // Logs "true"

这篇关于在 JavaScript 中实现单例的最简单/最干净的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆