为什么我的Singlton常数不能保持不变

时间:2019-05-26 21:52:42

标签: node.js module singleton

我正在尝试创建一个可以存储数据的单例模块。我希望只能使用设置器或公共功能来编辑此日期,而只能使用获取器来访问它。

我能够创建一个getter,setter和一个set函数。但是,当我尝试创建重置函数时遇到了无法解释的问题。

我将默认设置存储在const _defPorts中。

然后我分配let _myPorts = _defPorts。 (我想创建一个私有变量_myPorts,该变量用_defPorts中的常量值初始化。

问题是,当我开始设置新值时,我希望这只会更改_myPorts,它似乎也会更改我的_defPorts值。我不明白我在做什么错,或者我的const值如何被更改。因此,重置功能不起作用。

在我的console.log中,我仅显示_defPorts的值以显示其更改值的时间。

我觉得我的问题出在setPorts函数上,但是我不知道如何解决。任何帮助或建议,将不胜感激! :)

这是我要创建的Singleton模块:

'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 }

0 个答案:

没有答案
相关问题