How To Use Javascript Closures – POFTUT

How To Use Javascript Closures


What is closure? How can we use closure in our codes? etc. We can ask a lot of question about closures. Here is what are closures. Closure is a wrapper for different entities like functions.

Closure Scope

Closure is a block or scope of code where it has own environment and if it is called as function it will remember this environment. Let’s make thing more realistic and write an example code.

Test=function (a){ console.log(a); };

Test(1);

In this example we have created a closure named Test. Test closure provides a function and this function accepts a parameter named a. This parameter is printed to the console. As we have defined a closure as function we can call function with closure name.

Use Closure As Attribute

We can use closures as object attributes. Each closure is used separate attribute and called independently from other.

Test.Afunction=function (a){console.log(a);};
Test.Bfunction=function (){console.log("B function");};

Test.Afunction(1);
Test.Bfunction();

When a function is defined in a function a closure is used. When and eval is used a closure is used too.

 

How To Use Javascript Closures Infografic

How To Use Javascript Closures Infografic
How To Use Javascript Closures Infografic

LEARN MORE  What Is a Web Browser?

Leave a Comment