Tuesday, July 14, 2015

JavaScript Closures (Step 1 for App development)

JavaScript Closures

In this blog i like to write and discuss about the Closures in JavaScript, i am using JavaScript in SharePoint sites from 2007 version, In my first working assignment i was told to premeditate a Site template made using SPServices and Jquery to new SharePoint JavaScript client object model Site back in 2009, It was a Template which enables functionality of Twitter on SharePoint. But that time i just created and written everything in functions which were added under Global namespace automatically.

And this is normally we do in creating our applications or making some modifications, but with the advancement in client side programming and trend of Single Page applications and many other factors has introduced design patterns and writing javascript libraries.

To make such libraries one basic important concept is Closure.

A closure is concept made out of anonymous functions and a basic fact in javascript that an anonymous function can be returned from other functions, like it can also be assigned to a variable

Local variables defined within the containing function are available through the returned anonymous function and this is called Closure.

here we have a namespace Maddy and under that we have a function getStudentName which incorporates an anonymous function accessing local variable students and retrieving the value of name of student contained in students variable.

We have just returned the function to the original function.

The inner function is the closure in above example, it has three access chains, it can access its own variable and variables scoped to outer function and also can access Global function, but it can not access arguments directly of outer function, see this example:-