I am trying to create a singleton module that can store data. I want to be able to edit this date only with setters or public functions and only access it with getters.
I was able to create a getter, setter and a set function. However, I ran into a problem I cant explain when I tried to create a reset function.
I store my default settings in const _defPorts
.
I then assign let _myPorts = _defPorts
. (I want to create a private variable _myPorts
that is initialised with the constant values from _defPorts
.
The problem is when I start setting new values, which I expect will only alter _myPorts
, it seems to also change my _defPorts
values. I don't understand what I am doing wrong or how it is possible that my const value is being changed. Because of this the reset function does not work.
In my console.log
I am only displaying the value of _defPorts
to show at which point it changes value.
I feel my problem is with the setPorts
function but I do not know how to fix it. Any help or advice would be greatly appreciated! :)
This is the Singleton Module I am trying to create:
'use strict'
let activeConfig = (function () {
const _defPorts = {
http: 80,
https: 443,
secure: false
}
let _myPorts = _defPorts
let setPorts = function (value) {
console.log('SP->', _defPorts)
if (value) {
Object.keys(value).forEach((key) => {
if (typeof _myPorts[key] !== 'undefined') {
_myPorts[key] = value[key]
}
})
}
}
return {
setPorts: setPorts,
resetConfig: function () {
console.log('RC->', _defPorts)
_myPorts = _defPorts
},
get instance() {
console.log('GI->', _defPorts)
return this
},
get ports() {
console.log('GP->', _defPorts)
return _myPorts
},
set ports(value) {
return setPorts(value)
}
}
})()
module.exports = activeConfig
This is the code I am testing it with:
'use strict'
const {
ports,
instance: activeConfig
} = require('./activeConfig/activeConfig')
console.log('1 ->', activeConfig)
console.log('2 ->', activeConfig.ports)
activeConfig
.setPorts({
secure: true,
http: 8080
})
console.log('3 ->', ports)
activeConfig.ports = {
secure: true,
https: 4444
}
console.log('4 ->', ports)
console.log('RESET')
activeConfig.resetConfig()
console.log('5 ->', activeConfig.ports)
This is the console log output:
GP-> { http: 80, https: 443, secure: false }
GI-> { http: 80, https: 443, secure: false }
1 -> {
setPorts: [Function: setPorts],
resetConfig: [Function: resetConfig],
instance: [Getter],
ports: [Getter/Setter]
}
GP-> { http: 80, https: 443, secure: false }
2 -> { http: 80, https: 443, secure: false }
SP-> { http: 80, https: 443, secure: false }
3 -> { http: 8080, https: 443, secure: true }
SP-> { http: 8080, https: 443, secure: true }
4 -> { http: 8080, https: 4444, secure: true }
RESET
RC-> { http: 8080, https: 4444, secure: true }
GP-> { http: 8080, https: 4444, secure: true }
5 -> { http: 8080, https: 4444, secure: true }