JavaScript: Private variables

  Kenneth Truyers        2012-04-28 11:46:34       4,745        3    

The first thing you often hear when talking about JavaScript is often “JavaScript doesn’t have visibility modifiers, hence it doesn’t support private variables”. This is only valid for 50%, because JavaScript indeed doesn’t have visibility modifiers (public, private, friend) but it has closures and function scopes. With these tools we can make variables private. Let’s take the following function:

var names = ["Kenneth", "John", "Marc", "Robert"];

var lookup = function (index) {
    return names[index];
}

alert(lookup(0));

As you can see the variable “names” is public (and global) and can be accessed by any code running. A first thing that we can do is simply put the array in the function:

var lookup = function (index) {
    var names = ["Kenneth", "John", "Marc", "Robert"];
    return names[index];
}

alert(lookup(0));

This is of course not very optimal because it will reinitialize the Array every time we execute the function.

What you can do is use the fact that functions are first class objects and use a closure:

var lookup = (function () {
    var names = ["Kenneth", "John", "Marc", "Robert"];
    return function (index) {
        return names[index];
    };
} ());

alert(lookup(0));

In this last example we declare a function and execute it immediately (the outer function). This function declares first the Array (and thereby the scope is confined to that function). After that it returns a function that looks up the index in the Array.

Now we have defined the Array only once (while executing the outer function), but because the function that looks up the value in the Array is contained within the same scope as he outer function, the Array will still be available when the function is called.

This is only one of the many advantages that closures in JavaScript give you. It’s really a very good and powerful part of the language. Understanding this completely can be tricky, but once you get it, you’ll start to see the beauty of JavaScript.

Source : http://www.kenneth-truyers.net/2012/04/22/private-variables-in-javascript/

JAVASCRIPT  PRIVATE VARIABLE  CLOSURE 

       

  RELATED


  3 COMMENTS


paulkd [Reply]@ 2013-07-11 04:56:26

You have a typo in your last example.

 

You need to return names[index]

paulkd [Reply]@ 2013-07-11 05:00:14

Seriously? you are displaying my email address!

NightCat [Reply]@ 2013-07-11 11:35:42

We have changed the logic and hide the email. Sorry for the inconvenience.



  RANDOM FUN

Vitamin water label

If you woke up tired, you need more sleep. If you woke up drooling on your desk, you need a new job. If you woke up with a headache, somewhere in clarke quay, with dried mee goreng stuck to your face, you probably need answers, and a drink. Why not this product, huh? It's got potassium and b vitamin