stale closure const something = (value) => {
const r1 = Math.floor(Math.random() * 100);
const inside = () => {
const r2 = Math.floor(Math.random() * 100);
console.log({ r1, r2, value });
};
return inside;
};
const first = something("first");
const second = something("second");
first();
second();
first();
second();
first();
🡇🡇🡇 {r1: 12, r2: 22, value: "first"}
{r1: 78, r2: 45, value: "second"}
{r1: 12, r2: 11, value: "first"}
{r1: 78, r2: 40, value: "second"}
{r1: 12, r2: 80, value: "first"}
参考https://codesandbox.io/s/js-stale-closure-m26tdw?file=/index.js |
|