闭包

什么是闭包?

当一个内部函数被其外部函数之外的变量引用时,就形成了一个闭包。

闭包这名字起得有点奇怪啊。

如下面例子
数A的内部函数B被函数A外的一个变量 c 引用。变量c是在outer function的外面,然后调用了A,而调用A A又要调用B。相当于c用了B(B是一个内部函数)。。就这么绕
举个例子

    function A()
    {
        
        function B()
        {
            console.log("hello,world")
        }//inner function over here
        
    return B;
    }//outer function over here
    
var c=A();
c();//hello word;

也可以这么写

function A()
    {
        
        function B()
        {
            console.log("hello,world")
        };
        
    return B
    }
    
A()();//hello,world

还可以这么写

    function A()
    {
        
        return function B()
        {
            console.log("hello,world")
        }();
        

    }
    
A();//hello,world

但是不能这么写

    function A()
    {
        
        function B()
        {
            console.log("hello,world")
        }();
        
    return B
    }()
    
A();

这里的关键是理解return B是啥意思。

如果是

    function A()
    {
        
        function B()
        {
            console.log("hello,world")
        };
        
    return B
    }
    
A();

那么结果是

闭包_第1张图片
image.png

返回函数本身。

总结

如果返回的是一个函数,那么调用的时候一定注意不能只调用外层,两层都要调用。

你可能感兴趣的:(闭包)