
132
|
第
5
章
模块化模式与实践
这样的
calculator
使用起来也很简单,但现在我们可以执行异步操作。即
使其他使用者也在进行各自的计算,由于每个用户都有自己的状态,所以
数据不会受到污染 :
import { getCalculator } from './calculator'
const { add, multiply, calculate } = getCalculator()
add(3)
add(4)
multiply(-2)
calculate() // <- -14
即使使用之前的双文件案例,也不会有任何问题,因为每个文件都有自己
独立的
calculator
:
// a.js
import { getCalculator } from './calculator'
const { add, calculate } = getCalculator()
add(3)
setTimeout(() => {
add(4)
calculate() // <- 7
}, 100)
// b.js
import { getCalculator } from './calculator'
const { add, calculate } = getCalculator()
add(2)
calculate() // <- 2
正如上面展示的那样,即使使用现代语言结构和
JavaScript
模块,共享状
态也很容易产生复杂性。因此,我们应该始终努力让可变状态尽可能地靠
近其使用者。