【发布时间】:2019-10-13 17:29:26
【问题描述】:
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 once
calling several times
calling several times
calling several times
当第一块代码返回时:
runs only once
runs only once
runs only once
谁能向我解释一下 Javascript 引擎在后台做了什么?因为我觉得当你使用闭包时,输出会根据内部和外部函数内部的内容而有所不同。
【问题讨论】:
-
你没有在这里调用函数,
const run = initialize你只是引用了这个函数,而在第二个 sn-p 中你调用了返回一个函数的函数,你调用了它几次 -
Initialize 是一个接受参数的函数,并返回一个接受参数的函数。你需要做
run(1)(x); -
您是否忘记在顶部示例中的
initialize()调用中包含()?因为如果没有,你有一个函数引用,当你多次调用run(1)时,你只是调用initialize3 次 -
哦,是的,我的错,我忘记了 (),但添加 () 仍然会产生相同的输出。
-
我会再检查一次;尽管您的函数签名令人困惑,但它现在应该可以工作了。
标签: javascript closures