2-6-选择题,我的理解【下】

来源:2-6 选择题

我学习太差被关起来了

2019-12-09 17:27:51

为了更好地理解 2-6-选择题 以及闭包,我再举一例:

function fun()
{
    console.log("This is fun");

    function f1()
    {
        console.log("This is f1");
        return f2;
    }

    function f2()
    {
        console.log("This is f2");
    }

    return f1;
}

console.log(fun()()());


从代码中明显可见:

函数fun的返回值是f1函数,函数f1的返回值是f2函数,函数f2没有返回值(默认为undefined)。


我的分析如下:

【第1步】fun():执行fun函数。

结果:输出"This is fun",返回f1函数。

【第2步】fun()():fun()相当于f1函数,因此fun()()相当于f1(),即执行f1函数。

结果:输出"This is f1",返回f2函数。

【第3步】fun()()():f1函数返回值为f2函数,因此f1()(即fun()())相当于f2,因此fun()()()相当于f2(),即执行f2函数。

结果:输出"This is f2"。

【第4步】console.log(fun()()()):f2函数的返回值为undefined。

因此,结果:输出undefined。


程序运行结果截图如下:

http://img.mukewang.com/climg/5dee13490899f33903200253.jpg


分析与运行结果一致,从而验证了分析是正确的。

写回答

2回答

好帮手慕慕子

2019-12-09

同学你好, 其实同学两个例子举的都是可以的,只不过第二个例子通过输出++n的值,可以更好的展示出闭包的效果。输出结果示例:

http://img1.sycdn.imooc.com/climg/5dee23d609c82e3203210189.jpg

如果帮助到了你,欢迎采纳,祝学习愉快~

0

我学习太差被关起来了

提问者

2019-12-09

上面的例子举得不好,这里补充一个:

var n = 666;

function fun()
{
    console.log("This is fun");
    console.log(n);
    var n = 233;

    function f1()
    {
        console.log("This is f1");
        console.log(++n);
        return f2;
    }

    function f2()
    {
        console.log("This is f2");
        console.log(++n);
        return ++n;
    }

    return f1;
}

console.log(fun()()());


0

0 学习 · 14456 问题

查看课程