首页 > 解决方案 > 为什么我的单顿常数不能保持不变

问题描述

我正在尝试创建一个可以存储数据的单例模块。我希望能够仅使用 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 }

标签: node.jsmodulesingleton

解决方案


推荐阅读