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 引擎在后台做什么吗?因为我觉得当你使用闭包时,输出会根据内部和外部函数内部的内容而有所不同。
1 回答
墨色风雨
TA贡献1853条经验 获得超6个赞
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;
}
}
通过将第一行更改为实际调用initialize并返回一个函数,上面按预期运行
添加回答
举报
0/150
提交
取消