Should I avoid using top-level variables in module?

3560 views javascript
1

I'm writing code with React, and I'm trying to move some logics to modules, but I'm confused.

I have been writing modules like following lines.

// fooModule.js
let count = 0

export function countUp() {
    count += 1
}

export function getCount() {
    return count
}

This count variable can't be access from outer module as expected.

However, I noticed this variable status is keeping, When I twice importing this module, the variable status has shared in both.

So, Should I change to following?

// fooModule.js
export function countUp() {
    return count += 1
}

// someClass.js
import { countUp } from './fooModule.js'

const count = 0
const newCount = countUp(count)

Thanks.

answered question

require requires it once, then every call after that references the same result. This is how circular references are OK. If you want to create separate instances, you should use a class, export the class, then create instances of the class.

you could export a class and create instances if you want to keep state

1 Answer

3

Your second code won't work, because count is not in scope in fooModule, because you created it in someClass. If you want each importer of fooModule to have a separate binding for count, one option would be to export a function that, when called, creates a count variable, and returns a function that increments it and returns the new count:

// fooModule.js
export function makeCount() {
  let count = 0;
  return () => {
    count++;
    return count;
  };
}

// someClass.js
import { makeCount } from './fooModule.js';
const counter = makeCount();
console.log(counter()); // 1
console.log(counter()); // 2

Or, with generators:

// fooModule.js
function* makeCount() {
  let count = 0;
  while (true) {
    count++;
    yield count;
  }
}

// someClass.js
const counter = makeCount();
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2

posted this

Have an answer?

JD

Please login first before posting an answer.