I am seeing this pattern these days for nodeJS implementation, where in we have the following code for my Module:
class Foo {
bar() {
console.log('bar');
}
}
module.exports = Foo;
Then when I do a require and finally say new to create an instance of the class.
var Foo = require(./foo);
var myFoo = new Foo();
myFoo.bar();
This pattern according to me will keep creating multiple instances of class Foo, everytime it is called.
The other pattern could have been what i am used to where in my foo.js would be.
module.exports = {
bar: function() {
console.log('bar');
}
};
And then i just require and call bar.
var foo = require(./foo);
foo.bar();
Question would these two behave the same? Will the second pattern keep creating objects everytime I require and call bar on the object?
Isn't creating singleton pattern a good idea in case 1 as we are used to in other languages, wherein we keep serving the same instance if it has already been created once?
This pattern according to me will keep creating multiple instances of class Foo, everytime it is called.
Yes, that's the purpose. Though new Foo();
is only executed once in your example as well.
would these two behave the same?
No.
Will the second pattern keep creating objects everytime I require and call bar on the object?
No. require()
calls are cached, they return the same module every time.
Isn't creating singleton pattern a good idea?
No, a singleton is rarely a good idea if it contains any state. Your example does not, but where class
es are used in Node.js they usually do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With