Quantcast
Channel: JavaScript – iAdvise blog
Viewing all articles
Browse latest Browse all 14

5 Minute JavaScript #7 Closures

$
0
0

In the previous blogpost we discussed a way to reduce the amount of global variables by using namespaces. Today, we will be looking into a different way to hide functions and variables.

If you write JavaScript code on a regular basis (without being an expert) you might have heard about ‘closures’. While closures are becoming increasingly popular in other programming languages as well, JavaScript allows you to take them one step further.

Sometimes you want to run a block of code, define properties, etc without having to worry about the global object (5 MIN JS #4). If this is the case you could use a closure function to which you can bind your variables.

<script>
    var free = 'We want this variable to be global';
    var bound = 'We want to make this variable non-global';
</script>

Replaced this by:

<script>
var free = 'A free variable';
(function(){
    var bound = 'A bound variable to an anonymous function';
    function boundFunction () { /* cannot be called outside the closure */ }
}());
</script>

This is a function that is executed immediately. This means that the code result might be the same, but in the second example the ‘bound’ variable isn’t added to the global object. The difference between the ‘free’ and ‘bound’ variable is that the ‘bound’ variable is cleaned up after the function execution ends. This happens because its context is finished executing and it isn’t bound to a higher scope (such as the global object).

Some frameworks help you in writing better code without you knowing it. For example in jQuery, you are advised to use the $(document).ready(function() { }); function. Thanks to jQuery the programmer is actually using a closure, he’s defining a function that is passed along as parameter to the ready function. But this also means that all the variables defined while initializing are also set to ‘non-global’.



Viewing all articles
Browse latest Browse all 14

Latest Images

Trending Articles





Latest Images