简体   繁体   English

跨模块共享计数器变量不符合预期

[英]Sharing counter variable across modules doesn't behave as intended

A strange one...一个奇怪的...

A colleague has a counter (value) which they would like to share across files/modules of their application.一位同事有一个计数器(值),他们希望在其应用程序的文件/模块之间共享该计数器(值)。 Normally, I would say just pass the counter around... but they didn't want to do that for various reasons.通常情况下,我会说只是绕过柜台……但他们出于各种原因不想这样做。

So - fairly straight forward solution: Create a module, have a counter as a variable scoped to that module.所以 - 相当直接的解决方案:创建一个模块,将计数器作为作用域为该模块的变量。 Export an object with two methods: one to update the counter, and one to read the counter.使用两种方法导出 object:一种更新计数器,一种读取计数器。

Require the module where needed - and use the methods to interact with the counter.在需要的地方需要模块 - 并使用方法与计数器交互。

However, when passing in 1, setCounter would sometimes add two digits.但是,当传入 1 时,setCounter 有时会添加两位数。 We don't have this issue with a getter or setter... I'm puzzled as to why setCounter skips?我们对 getter 或 setter 没有这个问题......我很困惑为什么 setCounter 会跳过? We also ran it in isolation and it still skipped... This should work.我们也单独运行它,但它仍然跳过了……这应该有效。 I don't know why it isn't.我不知道为什么不是。 Am I missing something super obvious?我错过了一些非常明显的东西吗?


let _counter = 1223

module.exports = {
  /*
  setCounter: (x) => {
    _counter = _counter + x // where x is 1 it adds 2!!! why??
  },
  getCounter: () => {
    return _counter;
  }
  */

  get getCounter(){
    return _counter
  },

  set setCounter(value){
    _counter = _counter + value // does not skip _counter++ 
  }

}

Edit编辑

I've no idea why - but its now started working as intended??我不知道为什么 - 但它现在开始按预期工作了?


let _counter = 1223

module.exports = {
  
  setCounter: (x) => {
    _counter = _counter + x;
  },
  getCounter: () => {
    return _counter;
  },
  
}

Just tested again, and it now works.... makes no sense.刚刚再次测试,它现在可以工作了……没有意义。 I should probably delete this question, but some people have taken the time to reply.我可能应该删除这个问题,但有些人已经花时间回复了。


let _counter = 1223

module.exports = {
  setCounter: () => {
    _counter = _counter + 1;
    return _counter // or return ++counter
  },  
}

Try to do a simple setter instead.尝试做一个简单的二传手。

i = getCounter();
i++;
setCounter(i);

where the setter is二传手在哪里

set setCounter(value){
    _counter = value;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM