Diplomatic immunity through javascript

Would you love to be able to waltz in to a place, piss all over the floor, without anybody saying or doing anything to you? And what’s more: even if they wanted to punish you, you could make them  follow a process that you yourself defined. Haw haw!

Anonymous, self-executing functions can allow you to do this. They’re kind of like diplomatic immunity for your browser and can be very powerful.

(function(){/*
    Oooh it's so cozy in here. I have access to all
    global variables but I can do what
    I like and no-one will know!
    Now I'm going to do some private things.
*/

var privateVar = "I'm so lonely in here";
var privateFunction = function(s){ alert(s) };

/*

Okay, maybe I want to share something with the
    outside world but let's namespace it just in case:

*/

return namespace = {
           publicFunction : function(q){
               return function(a) {
                privateFunction(q + privateVar + a)
               }
            }
};

})();

We can’t access any of the private variables or functions from outside our anonymous function, thus avoiding collisions and overwriting, but we can return public functions that do! namespace.publicFunction is able to see, use and modify our private variables, but only in the way in which we want it.

It’s even possible to throw a bit of curry in there to spice it up. Calling namespace.publicFunction and passing it an argument (in this case a question) returns another anonymous function that expects an argument (an answer) and will then use our private variables to construct a little dialogue.

We would call it like this:

namespace.publicFunction("How are you?n")("nThat's too bad");

The example is basic and doesn’t make much practical sense but it demonstrates the way scope works in javascript and it can be a simple but handy tool to have in your arsenal.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: