Javascript closure

The following program returns "local" and, according to the manual, I am m reading, it is designed to demonstrate the phenomenon ofclos`

I do not understand why, in the end, to call the parentfunction, it assigns it to the variable "child" and then calls "child".

Why this doesn't work just by writing parentFunction (); in the end?

var variable = "top-level";
function parentFunction() {
  var variable = "local";
  function childFunction() {
    print(variable);
  }
  return childFunction;
}

var child = parentFunction();
child();
+3
source share
3 answers

, ( childFunction) ( ). parentFunction childFunction, !

, ...

var child = parentFunction();

... childFunction, childFunction , , , .

parentFunction childFunction, :

...

return childFunction;

To:

return childFunction();

( JSON, ) , javascript, javascript.

+2

parentFunction() , var child. child() , parentFunction().

parentFunction(); , , . :

parentFunction()();

: http://jsfiddle.net/USCjn/

: :

function outer() { // outer function returns a function
    return function() {
        alert('inner function called');
    }
}

x = outer(); // what is now in x? the inner function

// this is the same as saying:
//    x = function() {
//        alert('inner function called');
//    }

x(); // now the inner function is called

: http://jsfiddle.net/bBqPY/

JavaScript ( ( ...)). , , , , , . , . :

x = f();

- f , ( , , , ) x. :

x = f()();

- f, , ( ) x .

f , . . JavaScript , - , , .

, JavaScript.

2016

, :

function outer() {
    return function() {
        alert('inner function called');
    }
}

:

let outer = () => () => alert('inner function called');

ES6 .

+6

, , child, variable, ​​ parentFunction , ​​, child() .

The only way to create a variable scope in javascript is with the body of the function. Usually thrown variableinside parentFunctionafter function return.

But since you declared a function inside parentFunctionthat referenced variablein that scope and passed it from parentFunction, variableto is parentFunctionsaved using the link made in the new function.

This protects variableagainst external manipulations, with the exception of functions that close around it inside parentFunction.

+1
source

Source: https://habr.com/ru/post/1793776/


All Articles