What is Closure?
In simple terms, Closure is nothing but a function which is defined inside another function. the closure has access to all the local variables, outside function variables and global variables.
Problem Statement
To understand this in a better way, consider the following result of code.
- Problem Statement
1let name = "Ganesh"23function getMyName() {4 console.log("Name is " + name)5}67name = "Mani"89getMyName() //what will be the output here?
This kind of scenario is common in web development(front-end as well as backend). we will define a function and call the function later some point of time.
2. Problem Statement
1function getMyName() {2 let name = "Ganesh"34 return function() {5 console.log(name)6 }7}89let name = "Mani"1011// create a function12let myname = getMyName()1314// call it15myname() // What will it show?
To understand this concept, first, we need to understand the concept of Lexical Environment
Lexical Environment
Lexical Environment is nothing but maintaining the state of the particular function and its outer environment state, variables.
Every inner function will have a local variable, inner function can also access the parent function variable and global variable.
Maintaining the scope of the particular function is nothing but a Lexical Environment.
Coming back to Problem Statements...
Now, if we come back to the problem statements, the problem statement #1 would return the value as "Mani"
Because ,The value gets updated since we have defined it as Global Variable.
Now, in Problem statement #2, we have defined a function called getMyName(). inside the function, we have defined a variable called name which is nothing but a parent function variable.
we are returning a function from the getMyName() function.
Now, if we define the same variable called name in the global context and execute the getMyName().
it won't change the value of it. because getMyName() returning a function which is nothing but a Closure will hold the variable state and value for the particular environment
https://output.jsbin.com/qikuginowe
javascript first look inside the inner function, then it will look in the parent function. finally, it will go look in the global variables.
Closure - Practical Implementation
Using Closure instead of objects
If you are familiar with OOPS concepts, you will know that concept of "this", which will refer the context of the class
Let's try to write a function using OO concept and then we will see how we can rewrite that with Closures.
1function User() {2 this.firstname = "John"34 this.lastName = "Robert"5}67User.prototype.getFirstName = function getFirstName() {8 console.log(this.firstname)9}1011User.prototype.getLastname = function getLastname() {12 console.log(this.lastName)13}1415User.prototype.showFullName = function showFullName() {16 console.log(this.firstname + " " + this.lastName)17}1819module.exports = User
we are creating a function called user and add the function getFirstName, getLastName and showFullName for the particular user function and access the function variable with thiskeyword.
To call this particular function we need to create an new instance of it and call the particular function
1let User = require("./user")23let data = new User()4data.showFullName()
it will show me something like "John Robert"
Now, let's see how we can rewrite this with Closures
1function User() {2 let firstName = "Will"34 let lastName = "Smith"56 return {7 getFirstName: function() {8 console.log(firstName)9 },1011 getLastName: function() {12 console.log(lastName)13 },1415 showFullName: function() {16 console.log(firstName + " " + lastName)17 },18 }19}2021module.exports = User
we are defining a user function like we did before, then instead of binding the function. we are returning those function from the parent function user.
Note : return functions are nothing but closures.
Now, if i want to call this function , we have to do something like
1//using Closure in Javascript23let userClosure = require("./user_closure")45let closureresult = userClosure()67closureresult.showFullName()
it will return "Will Smith" as output.
This is one of the real-time use cases where can try to implement Closures instead of going with thiskeyword.
Quiz :
Try to solve this problem and comment your result in this post and explain me how it works.
1function doIncrement() {2 let counter = 034 return function() {5 counter++6 return counter7 }8}910let increment = doIncrement()1112console.log(increment())13console.log(increment())14console.log(increment())15//What is the result ?
That's it for this week. try to implement this in a real time usecases, so that you can grab
Comments
Post a Comment