const run = initialize;run(1);run(1);run(1);function initialize(index) { console.log('runs only once'); return function(index) { console.log('useless code to use closure to make sure initialize only runs once'); return index; }}這不起作用,但我不確定為什么,因為下面的代碼按預期工作,并且只在外部函數中運行一次代碼,同時多次運行內部函數。const getIndex = bigStuff();getIndex(500);getIndex(600);getIndex(700);function bigStuff(index) { const myArray = new Array(300).fill('3'); console.log('created once'); return function(index) { console.log('calling several times'); return myArray[index]; }}第二段代碼返回:created oncecalling several timescalling several times calling several times 雖然第一塊代碼返回:runs only onceruns only onceruns only once有人可以向我解釋 Javascript 引擎在后臺做什么嗎?因為我覺得當你使用閉包時,輸出會根據內部和外部函數內部的內容而有所不同。
在 Javascript 中使用閉包的函數的意外輸出
翻閱古今
2021-11-18 20:50:09