I've been trying to use a Single JavaScript object in multiple files. For that I chose singleton design pattern in JavaScript.
mySingleton.js
var mySingleton = (function () {
var instance;
function init() {
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "Im also private";
var privateRandomNumber = Math.random();
return {
publicProperty: "I am also public",
publicMethod: function () {
console.log( "The public can see me!" );
},
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
getInstance: function () {
if ( !instance ) {
instance = init();
console.log("Newly creating an object");
}
return instance;
}
};
})();
module.exports = mySingleton;
And i'm Accessing the The above object in a separate node js file. As showed in following code
test.js
var singleton = require('./mySingleton');
var obj = singleton.getInstance();
console.log(obj.publicProperty);
console.log('random number value:'+obj.getRandomNumber());
test2.js
var singleton = require('./mySingleton');
var obj = singleton.getInstance();
console.log(obj.publicProperty);
console.log('random number value:'+obj.getRandomNumber());
When i execute the above two files each time a new javascript object is creating. But I want to use the same JavaScript object in multiple files.
Thanks in advance....
So Can anyone please give any suggestion to achieve the above functionality.
The issue is that you are running test.js and test2.js independently. When you execute test.js, it creates a global context where obj
binds to global scope of test.js. After the execution is complete, that context is destroyed and a new context is created for test2.js. Hence the instance
variable inside getInstance
function does not find the instance and creates a new one. To correctly use single pattern you need to use same singleton
variable to get instances.
Thus once you have created singleton
using
var singleton = require('./mySingleton');
you need to get all the instances using this variable only. Since the singleton property is arising due to closure of execution of anonymous function which returns object to mySingleton
You're calling them individually which will not work, every time you call node test.js you're creating a new run time variable:
If you were to include them into a main package and run it, you would see that it works just fine:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.