在 JavaScript 中实现单例的最简单/最干净的方法

编程入门 行业动态 更新时间:2024-10-09 15:15:22
本文介绍了在 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 中实现单例的最简单/最干净的方法

本文发布于:2023-10-19 17:43:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508288.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最简单   干净   方法   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!