nodejs如何实现单例
时间: 2024-01-31 07:04:54 浏览: 35
以下是NodeJS实现单例模式的例子:
```javascript
// 使用闭包实现单例模式
function Singleton() {
let instance;
Singleton = function() {
return instance;
}
Singleton.prototype = this;
instance = new Singleton();
instance.constructor = Singleton;
return instance;
}
const s1 = new Singleton();
const s2 = new Singleton();
console.log(s1 === s2); // 输出:true
```
```javascript
// 使用ES6 class实现单例模式
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
const s1 = new Singleton();
const s2 = new Singleton();
console.log(s1 === s2); // 输出:true
```
```javascript
// 使用Symbol实现单例模式
let instance = Symbol('instance');
function Singleton() {
if (Singleton[instance]) {
return Singleton[instance];
}
Singleton[instance] = this;
}
const s1 = new Singleton();
const s2 = new Singleton();
console.log(s1 === s2); // 输出:true
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)