Answer the question
In order to leave comments, you need to log in
How to apply singleton pattern in node.js?
How to apply singleton pattern in node.js in different files without using global object?
App structure
app/app.js
app/files/Shop.js
app/files/Fruits.js
app.js
let Shop = require("./files/Shop");
let shop = new Shop();
let Shop = require("./Shop");
let shop = Shop.getInstance(); // цель - получение ссылки на созданный экземпляр в app.js
class Shop {
constructor() {
this._store = null;
}
setStore(value) {
this._store = value;
}
getStore(value) {
return this._store;
}
}
module.exports = new Shop();
let shop = require("./files/Shop");
shop.setStore("apple");
let shop = require("./Shop");
shop.getStore(); // "apple"
Answer the question
In order to leave comments, you need to log in
You don't show anywhere how you do the export.
By themselves, CommonJS modules already implement Singleton.
// app/app.js
const Shop = require("./files/Shop");
const shop = new Shop();
module.exports = shop;
// app/files/Fruits.js
const shop = require('../app'); // shop, созданный в app.js, будет всегда один и тот же
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question