Day 5 : JavaScript Closures
In this blog, we are going to understand the closure concept in JavaScript.
Closures in JavaScript :
- The closures are the important and some what complex concept in JavaScript.
- Before we go to closures we have to known about life of variables and scopes in JavaScript.
Life of variables :
1) Global variables -
Global variables have long lives. They are created at the beginning of the program and they live until the page or program is discarded.
2) Local variables -
Local variables have short lives. They are created when the function is invoked and deleted when the function is finished.
Scope :
- As we all know we can’t get data from an outside scope.
- JavaScript doesn’t have the public, private, protected access modifiers. For security or accessibility in JavaScript we use closures.
- Every closure has three scopes: Local scope, Outer function scope, Global Scope.
Understanding Closures :
- The closure is feature of JavaScript where function has access to it’s own scope, outer scope(i.e adjacent class), global scope.
- Every time when function is created , the closure is created.
- A closure gives access to an outer function scope from inner function.
- Closures contain the self invoking function i.e IIFE.
- Closure is some what same as nested function.
- Example :
<script>
var str= (function() {
function _concat(a,b) {
return a+b
}
return {
concat:_concat
}
})();
var obj=str.concat("JavaScript"," Closures");
alert(obj);
</script>
- In above example, we understand that the closure has a nested as well as self invoking function. We assign a variable to self invoking function, created the object of that function and passed the arguments to that function.
- The output shows that we implement the closures.
Thank You!!!
For more understanding watch below video :
JavaScript Day 2 Global Pollution : Day 2 Global
JavaScript Day 2 Undefined and Hoisting : Day 2 Undefined
JavaScript Day 3 : Day 3
JavaScript Day 4 : Day 4
Comments
Post a Comment