Closing in the JavaScript - it is a function that contains variables from the outer scope. That is, it closes the external variables in itself.
Inside function A, you can run function B, which can use the variables of the external function A.[konec_stroki]After the function is executed, its internal variables are automatically removed from memory by the garbage collector. [konec_stroki]But if the variables of the external function A are used in the internal function B, the variables are not deleted.
JavaScript
// scope global
var a = 'Good morning';
function something()
{
// scope inner1
var b = 'inner1';
return function()
{
// scope inner2
return b; // closing . b taken from the scope inner1
}
}
var myFunc1 = something();
myFunc1();
JavaScript
function sayHello()
{
// A local variable that is only available in a loopback
var hello = "Hello, world!";
var say = function()
{
console.log(hello);
}
return say;
}
var sayHelloClosure = sayHello();
sayHelloClosure();
// On the screen we will see "Hello, world!"
Когда внутренняя функция ссылается на переменную из внешней функции, это называется замыканием
JavaScript
function foo(msg) {
var fn = function inner(){
return msg.toUpperCase();
};
return fn;
}
var helloFn = foo( "Hello!" );
helloFn(); // HELLO!