So I'm struggling to understand which way of returning a class instance in getter methods is better
Here is version 1
Products.js
class Products {}
module.exports = {Products}
Price.js
class Price {}
module.exports = {Price}
index.js
const { Products} = require('./Products.js')
const { Price} = require('./Price.js')
class General {
get products() {
return new Products()
}
get price() {
return new Price()
}
}
Here is version 2
Products.js
class Products {}
module.exports = new Products()
Price.js
class Price {}
module.exports = new Price()
index.js
const Products = require('./Products.js')
const Price = require('./Price.js')
class General {
get products() {
return Products
}
get price() {
return Price
}
}
Deep inside I have a feeling that it's more correct to initialize the instance of the class only when I'm trying to access it (version 1). However I couldn't find any pros or cons of each approach.
Can someone please confirm that one of this approaches can be considered as a bad practice? Maybe one of this methods has performance issues...
Also as far as I understand when exporting an instance of the class it's becoming a singleton which is an anti pattern as well