https://github.com/xeeo/nc-singleton
a simple singleton module to be used in your contructors
https://github.com/xeeo/nc-singleton
Last synced: 12 months ago
JSON representation
a simple singleton module to be used in your contructors
- Host: GitHub
- URL: https://github.com/xeeo/nc-singleton
- Owner: xeeo
- Created: 2015-09-18T16:25:55.000Z (almost 11 years ago)
- Default Branch: master
- Last Pushed: 2016-04-09T04:52:46.000Z (about 10 years ago)
- Last Synced: 2025-03-04T10:28:12.072Z (over 1 year ago)
- Language: JavaScript
- Size: 3.91 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# nc-singleton
A simple singleton module to be used inside your constructor.
## Usage
Let's assume you are working on a module. You use prototype and you want that all your new statements return the same instance.
```javascript
'use strict';
var singleton = require('nc-singleton');
var Cache = function Cache() {
return singleton.call(this, Cache);
};
Cache.prototype.setTime = function() {
this.time = new Date();
};
Cache.prototype.getTime = function() {
return this.time;
};
var cache = new Cache()
cache.setTime();
console.log(cache.getTime());
setTimeout(function(){
var cache = new Cache();
console.log(cache.getTime());
}, 4000);
```
It also works with ES6
```javascript
'use strict';
var singleton = require('nc-singleton');
let instance = null;
class Cache {
constructor() {
return singleton.call(this, Cache);
}
setTime() {
this.time = new Date();
}
getTime() {
return this.time;
}
}
let cache = new Cache()
cache.setTime();
console.log(cache.getTime());
setTimeout(function(){
let cache = new Cache();
console.log(cache.getTime());
}, 4000);
```
For testing just npm test :)
That's it.