- Modern JavaScript Web Development Cookbook
- Federico Kereki
- 181字
- 2021-07-02 14:50:00
Adding initialization checks
If you wish, you can make the .init() function more powerful by having the module crash if used without initialization:
// Source file: module_counter.2.js
/* @flow */
let name = "";
let count = 0;
let get = () => count;
let throwNotInit = () => {
throw new Error("Not initialized");
};
let inc = throwNotInit;
let toString = throwNotInit;
/*
Since we cannot initialize anything otherwise,
a common pattern is to provide a "init()" function
to do all necessary initializations. In this case,
"inc()" and "toString()" will just throw an error
if the module wasn't initialized.
*/
const init = (n: string) => {
name = n;
inc = () => ++count;
toString = () => `${name}: ${get()}`;
};
export default { inc, toString, init }; // everything else is private
In this fashion, we can ensure proper usage of our module. Note that the idea of assigning a new function to replace an old one is very typical of the Functional Programming style; functions are first class objects that can be passed around, returned, or stored.