#author("2023-10-03T17:33:14+09:00","default:ryuichi","ryuichi")
#author("2023-10-03T17:33:46+09:00","default:ryuichi","ryuichi")
* stale closure [#c09f153c]
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"}
- r1はfirstやsecondが作成された時に決定するので、first()、second()を何度実行しても変化しない
** 参考 [#gb64e40e]
https://codesandbox.io/s/js-stale-closure-m26tdw?file=/index.js