【问题标题】:Unexpected output from a function using closure in Javascript在 Javascript 中使用闭包的函数的意外输出
【发布时间】: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) 时,你只是调用initialize 3 次
  • 哦,是的,我的错,我忘记了 (),但添加 () 仍然会产生相同的输出。
  • 我会再检查一次;尽管您的函数签名令人困惑,但它现在应该可以工作了。

标签: javascript closures


【解决方案1】:

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 并返回一个函数,上述代码按预期运行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多