Wednesday 11 February 2015

Demystifying JavaScript Closures, Callbacks And IIFEs

We have already taken a close look at the contexts of variables and elevation, so today we will end our exploration by examining three of the most important and heavily used in modern JavaScript development concepts - closures, callbacks and IIFEs.
Closures

In JavaScript, a closure is any function that holds the reference to the variables of the scope of his father, even after the parent has returned.

This means practically any function can be considered a close, because, as we have seen in section variable range of the first part of this tutorial, a function can refer to, or have access to -
  •       variables and parameters in its own sphere of function
  •       the variables and parameters of external functions (parents)
  •       global variables.
So, chances are you've already used closures without knowing it. But our goal is not just to use them - is to understand them. If you do not understand how they work, we cannot use them properly. Therefore, we will divide the definition previous close in three easy points to understand.

Item 1: You can refer to variables defined outside the current function.



Try the example of JS Bin

In this code example, the PrintLocation () function refers to the variable of country and city parameter envelope function (father) setLocation (). And the result is that when setLocation () is called, PrintLocation () successfully used the variables and parameters from the old to the exit "You are in Paris, France."

Point 2: internal functions can refer to variables defined in the outer function, even after he has returned.



Try the example of JS Bin

this is almost identical to the first example, except this time PrintLocation () is returned within the outer setLocation (function), instead of being called immediately. Thus, the value is the inner PrintLocation CurrentLocation () function.

If alerted CurrentLocation like this - alert (CurrentLocation); - Let's get the following result:



As we can see, PrintLocation () is executed outside its lexical scope. It seems that setLocation () is gone, but PrintLocation () still have access to, and "remembers" its variable (country) and the (city) parameter.

A closure (internal function) is able to remember its surrounding area (external functions), even when running outside its lexical scope. Therefore, it can be called at any later point in your program.

Point 3: Functions stored inside variables external function by reference, not by value.



Try the example of JS Bin

Here CityLocation () returns an object containing two locks - get () and set () - and both refer to the city the external variable. Get () gets the current value of the city, while set () updates. "Sydney" - - instead of the default "Paris" option when myLocation.get () is called a second time, the (current) present value of the city is issued.

Thus, the closures can read and update your stored variables, and updates are visible to any closure have access to them. This means that the store closings references to their external variables, instead of copying their values. This is a very important point to remember, because they know that can lead to some difficult point logical errors - as discussed in "expressions of immediately invoked function (IIFEs)" section.

An interesting feature of closures is that the variables in a closure are automatically hidden. Closing data centers closed their variables without providing direct access to them. The only way to alter these variables is by accessing them indirectly. For example, in the last part of the code we saw that we can modify the variable town only obliquely using the get () and set () closures.

We can use this behavior to store private data on an object. Instead of storing the data as properties of an object, we can store it as variables in the constructor, and then use the closures and methods relating to these variables.

As you can see, there is nothing mystical or esoteric about closures - just three simple points to remember.

CALLBACKS:

In JavaScript, functions are first-class objects. One consequence of this is that the functions can be passed as arguments to other functions, and can also be returned by another
functions.

A function that takes other functions as arguments or return functions as its result is called a higher order function, and the function that is passed as an argument is called a callback function. It's called "callback", because at some point in time that is "called back" by higher order function.

Callbacks have many everyday uses. One is when we use the setTimeout () and setInterval () of the Object Browser - methods that accept and execute callbacks:



Try the example of JS Bin

Another example is when an event is attached to an element on a page. By doing that we are actually providing a pointer to a callback function to be called when the event occurs.



Try the example of JS Bin

The easiest way to understand how higher-order functions and callbacks job is to create his own. Therefore, we will create one now:



Try the example of JS Bin

Here we create a fullName () function takes three arguments - two for the name, and one for the callback function. Then, after the console.log () statement, put a function call that triggered the callback function actual call - function Card () defined below the fullName (). And finally, we call fullName (), which is passed Card () as a variable - without brackets - because we want to run immediately, but simply want to point out that for later use by fullName ().

We are moving from the definition of the function, not the function call. This prevents the callback to be executed immediately, which is not the idea behind callbacks. He spent the definition of functions that can be executed at any time and at any point of the function containing. Furthermore, because callbacks behave as if placed actually within that function, are closing practice: you can access variables and parameters of the function containing, and even variables from a global scope.

The callback can be an existing function as shown in the example above, or it can be an anonymous function, we create when we called the higher order function, as shown in the following example:



Callbacks are used heavily on JavaScript libraries to provide generalization and reuse. Allow for easy library methods and / or extended customization. In addition, the code is easier to maintain, and much more concise and easy to read. Whenever you need to transform your model repeated unnecessary based on more abstract / generic callbacks come to the rescue code.

Say we have two functions - one that prints information about the published and another that prints information about messages sent. We believe, but we realize that some of our logic is repeated in both functions. We know that having one and the same piece of code in different places is unnecessary and difficult to maintain. So what is the solution? We will illustrate in the following example:



what we have done here is to the pattern of repeated code (console.log (point) and var date = new Date ()) in a separate function, generic (publish ()), and leave only the specific data within other functions - who are now callbacks. Thus, with one and the same function that can print information for all things related - posts, articles, books, magazines and others. All you have to do is create a callback function for each type specialized call and pass it as an argument to the publish () function.