简体   繁体   中英

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.

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. We don't have this issue with a getter or setter... I'm puzzled as to why setCounter skips? 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;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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