node.js - 为什么我的单顿常数不能保持不变
问题描述
我正在尝试创建一个可以存储数据的单例模块。我希望能够仅使用 setter 或公共功能编辑此日期,并且只能使用 getter 访问它。
我能够创建一个 getter、setter 和一个 set 函数。但是,当我尝试创建重置功能时遇到了一个无法解释的问题。
我将默认设置存储在const _defPorts
.
然后我分配let _myPorts = _defPorts
. (我想创建一个私有变量_myPorts
,它使用来自_defPorts
.
问题是当我开始设置新值时,我希望它只会改变_myPorts
,它似乎也会改变我的_defPorts
值。我不明白我做错了什么,也不明白我的 const 值怎么可能被改变。因此,重置功能不起作用。
在我的console.log
我只显示值_defPorts
以显示它在哪个点改变值。
我觉得我的问题出在setPorts
功能上,但我不知道如何解决。任何帮助或建议将不胜感激!:)
这是我要创建的单例模块:
'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
这是我正在测试它的代码:
'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)
这是控制台日志输出:
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 }
解决方案
推荐阅读
- python - 具有不同功能的python多处理
- xamarin - 随图像尺寸变化的按钮定位
- angular - Angular2-JWT 包不再在 Angular 6 中工作(RXJS 导入问题)
- jquery - 需要用箭头键推进幻灯片放映图片
- python - Replace a line of a text file in python
- android - 如何在自定义 Listview 布局适配器中安排 Textview,放置在另一个 Textview 下方?添加了适配器支持
- c# - 从文件中读取随机行
- android - Phonegap App 在 PC 上检索数据,但在 Android 设备上不检索
- android - 动态更改所有工具栏图标颜色
- android - 位图有时为空