How to Use Closures in Your JavaScript Code - dummies

How to Use Closures in Your JavaScript Code

By Chris Minnick, Eva Holland

A closure is like keeping a copy of the local variables of a JavaScript function as they were when the closure was created. In web programming, closures are frequently used to eliminate the duplication of effort within a program or to hold values that need to be reused throughout a program so that the program doesn’t need to recalculate the value each time it’s used.

Another use for closures is to create customized versions of functions for specific uses.

In this example, closures are used to create functions with error messages specific to different problems that may occur in the program. All the error messages get created using the same function.

When a function’s purpose is to create other functions, it’s known as a function factory.

<html>
<head>
 <title>function factory</title>
 <script>
 function createMessageAlert(theMessage){
  return function() {
  alert (theMessage);
  }
 }
 
 var badEmailError = createMessageAlert(“Unknown email address!”);
 var wrongPasswordError = createMessageAlert(“That’s not your password!”);
 
 window.addEventListener(‘load’, loader, false);
 function loader(){
  document.login.yourEmail.addEventListener(‘change’,
badEmailError); document.login.yourPassword.addEventListener(‘change
‘,wrongPasswordError); } </script> </head> <body> <form name=“login” id=“loginform”> <p> <label>Enter Your Email Address: <input type=“text” name=“yourEmail”> </label> </p> <p> <label>Enter Your Password: <input type=“text” name=“yourPassword”> </label> </p> <button>Submit</button> </body> </html>

The key to understanding this example is the factory function.

function createMessageAlert(theMessage){
  return function() {
  alert (theMessage);
  }
 }

To use this function factory, assign its return value to a variable, as in the ­following statement:

var badEmailError = createMessageAlert(“Unknown email address!”);

The preceding statement creates a closure that can be used elsewhere in the program just by running badEmailError as a function, as in the following event handler:

document.login.yourEmail.addEventListener(‘change’,badEmailError);