What is a 'Closure'?

前端 未结 23 1768
星月不相逢
星月不相逢 2020-11-22 08:02

I asked a question about Currying and closures were mentioned. What is a closure? How does it relate to currying?

23条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 09:07

    Closure is very easy. We can consider it as follows : Closure = function + its lexical environment

    Consider the following function:

    function init() {
        var name = “Mozilla”;
    }
    

    What will be the closure in the above case ? Function init() and variables in its lexical environment ie name. Closure = init() + name

    Consider another function :

    function init() {
        var name = “Mozilla”;
        function displayName(){
            alert(name);
    }
    displayName();
    }
    

    What will be the closures here ? Inner function can access variables of outer function. displayName() can access the variable name declared in the parent function, init(). However, the same local variables in displayName() will be used if they exists.

    Closure 1 : init function + ( name variable + displayName() function) --> lexical scope

    Closure 2 : displayName function + ( name variable ) --> lexical scope

提交回复
热议问题