To make such libraries one basic important concept is Closure.
Local variables defined within the containing function are available through the returned anonymous function and this is called Closure.
Now lets see this in a series of examples:-
- Basic Closure example:-
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:-
Look at this example which does not use Closure:-
It will work perfectly and will give you output of 15.
Now if you use Closure and try to access arguments it wont work.
it will return '0' in alert and wont work.
So Closure can access local,outer and global variables but cant work with outer function arguments object.
- Closures have access to the outer function’s variable even after the outer function returns, also it stores references to the outer function’s variables;