Closure (nonfiction): Difference between revisions
No edit summary |
No edit summary |
||
Line 14: | Line 14: | ||
function showName (firstName, lastName) | function showName (firstName, lastName) | ||
var nameIntro = "Your name is "; | var nameIntro = "Your name is "; | ||
// this inner function has access to the outer function's variables, including the parameter | |||
function makeFullName () | function makeFullName () | ||
return nameIntro + firstName + " " + lastName; | return nameIntro + firstName + " " + lastName; | ||
} | } | ||
return makeFullName (); | return makeFullName (); | ||
} | } | ||
showName ("Michael", "Jackson"); // Your name is Michael Jackson
| showName ("Michael", "Jackson"); // Your name is Michael Jackson
| ||
</code> | </code> | ||
http://javascriptissexy.com/understand-javascript-closures-with-ease/ | http://javascriptissexy.com/understand-javascript-closures-with-ease/ |
Revision as of 20:58, 10 January 2019
In programming languages, a closure (also lexical closure or function closure) is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment. The environment is a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.
https://en.wikipedia.org/wiki/Closure_(computer_programming)
What is a closure?
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.
You create a closure by adding a function inside another function.
function showName (firstName, lastName)
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName ()
return nameIntro + firstName + " " + lastName;
}
return makeFullName ();
}
showName ("Michael", "Jackson"); // Your name is Michael Jackson
http://javascriptissexy.com/understand-javascript-closures-with-ease/