Javascript Closure Function

Javascript Closure Function

One of the most interesting concepts of Javascript Closure is the ability the retain/remember its value even after the closure. I attached several examples of how closure is used in javascript. Here is a simple example. A simple closure function.Closure is the concept where an inner function has access to variables from an outer function, even after the outer function has completed execution. In this case, the inside function has access to val1 (from the myfunction call), even though myfunction has already finished executing. This is because val1 is enclosed within the closure created by the inside function.The closure captures val1 as ‘First Value’. When result(‘Second Value’) is called, the inside function logs both val1 (from the closure) and val2 (passed during the call). As you can see above once you have created the function it will remember the name of person,  mybody and skirt. You can manipulate the data as you wish and this is perfectly fine.Closures: The functions body() and skirt() are closures. They “close over” the variables abody and askirt from their parent scope (inside createGf), allowing them to remember and modify the values even after createGf has finished executing.Encapsulation: The variables abody and askirt are encapsulated within the createGf function. They cannot be accessed directly from outside the function, providing controlled access through the body() and skirt() methods.newGf.skirt() reduces the skirt length from 30 to 25 and prints Skirt is getting shorter: 25. newGf.skirt() reduces the skirt length from 25 to 20 and prints Skirt is getting shorter: 20. newGf.body() increases the body size from 50 to 55 and prints Oopos Getting Fatter: 55. newGf.body() increases the body size from 55 to 60 and prints Oopos Getting Fatter: 60.
Related Posts
Leave a Reply

Your email address will not be published.Required fields are marked *