- testClosure is invoking a named function that accepts two arguments and returns an anonymous function, and sets t1 to be an anonymous function.
t1 is now an anonymous function that can be invoked and accepts one argument. When t1 is invoked it builds your string param arguments from the name function and the anonymous function and returns the result.
When ever you invoke the named function testClosure it is creating a closure. When you invoke the anonymous function it has access to the enclosed name function string params, and returns the all 3 params as a built string .
Closures in JS is one of the most powerful implementations that JavaScript offers. Learning how to and where to implement or where a closure is needed is learned by baby steps over a period of time.
The bigger your JavaScript library grows the more you'll find yourself needing closures.
Closures allow you to put a specific piece of data in a context out of reach of other context, and I find myself using them more inside loops than anywhere else.
Anonymous functions and closures work together most of the time. The best way to learn closures is to keep very persistent in learning a little more each day about closures and when the time comes you'll finally get it when you find yourself in a situation that would need a closure.
Below is an example where I'm making an AJAX call to a photo album on a remote server. The success function of the AJAX call holds an array of photos for the album. for each loop I'm invoking a name function that will return an anonymous function. The anonymous function is set to the button click event.
Every new button added to the DOM will have access to it's own personal enclosed url string param.
It is vital to learn and understand closures to be a good JavaScript programmer.
function testClosure(url) {
return function (ev) {
document.getElementById('myImg').url = url || 'http://www.dummyurl/dummy.png';
}
}
$.ajax({
type: "post",
url: "http://www.myurl.com",
data: 'photoalbum' = 45,
dataType: "json",
success: function (photos) {
for (var i = 0; i < photos.length; i++) {
var btn = document.createElement('input');
btn.type = 'button';
btn.onclick = testClosure(photos[i].url);
document.body.appendChild(btn);
};
}
});