只初始化一次

最后更新于:2022-04-02 03:24:06

[TOC] ## 仅仅初始化一次 bad ``` function whichSideOfTheForce1(name) { const light = ['Luke', 'Obi-Wan', 'Yoda']; const dark = ['Vader', 'Palpatine']; return light.includes(name) ? 'light' : dark.includes(name) ? 'dark' : 'unknown'; } whichSideOfTheForce1('Luke'); whichSideOfTheForce1('Vader'); ``` good ``` function whichSideOfTheForceClosure1(name) { const light = ['Luke', 'Obi-Wan', 'Yoda']; const dark = ['Vader', 'Palpatine']; console.log("run"); return (name) => (light.includes(name) ? 'light' : dark.includes(name) ? 'dark' : 'unknown'); } const whichSideOfTheForce2 = whichSideOfTheForceClosure1(); whichSideOfTheForce2('Luke'); whichSideOfTheForce2('Vader'); ```
';