
Sep 18, 2015
In today’s blog I will explain the concept of a closure in JavaScript. The best way to grasp this concept is by means of a step-by-step example. Let’s define a function prepareMessage that accepts one input parameter.function prepareMessage(msg) { … }Now inside this function you will define and initialise a variable message as follows,
var message = 'Message: ' + msg;The next step is what defines a closure. You will define an anonymous function that will be the return of prepareMessage and inside this function you will use the local variable message you have just declared.
function prepareMessage(msg) { var message = 'Message: ' + msg; var showMessage = function() { alert(message); } return showMessage; }Note that the prepareMessage function itself is not going to display any message, it prepares the message and then returns a handle to a function that will be display the message. What’s special here is the fact that this returned handle will allow the caller to display a message that has access to the local variable message defined when prepareMessage was first called even though the prepareMessage has already returned by the moment the caller is using the returned handle. To complete the demonstration we need to use the function above to prepare and then show a message.
var displayMessage = prepareMessage('Closure in action'); displayMessage();The result will be the output “Message: Closure in Action”. Note that after we returned from the call to prepareMessage the local variable message declared inside prepareMessage was kept alive and that is what allowed displayMessage() to display what we saw. This behaviour is what we call a closure. To summarise, if an outer function returns a handle to an inner function then all the local variables for the outer function will remain accessible to the inner function. You can think of a closure as the container for all those local variables that are still alive long after the outer function was called. To learn more about JavaScript we recommend Microsoft course 20480 - Programming in HTML5 with JavaScript and CSS3.
How do your Excel skills stack up?
Test NowNext up:
- Use a slicer to make better business decisions
- The best features in Office 2016!
- “If you can’t measure it…”
- No need for meeting notes anymore!
- Setting up your models in MVC
- Create a Chart Template in Excel
- Cascaded Dropdowns in Nintex Forms
- The Aussie Meat Pie of Managing Teams
- Introduction to Office 365 Video
- Entity Framework Code-First
Previously
- Put that marker down and Redact in Acrobat please!
- Understanding your customers with 6 questions
- New security features in Windows 10
- All About VLOOKUP() in Excel
- Creating a layout for Word and Excel
- Implementing paging easily
- Leadership, Management and Feedback
- Do the Quick Step in Outlook
- OneDrive for Business Gets Some Major Enterprise Updates
- Rounding Numbers in Excel, Part 2