Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Closures are essentially a way to create private variables.

For example, in Javascript:

    var fn = null;
    
    (function(){
        
        var temporary = 789;
        alert(temporary);
        
        var secret_private = 5;
        fn = function(){
            alert(secret_private);
        };
    
    })();
    
    fn();

In javascript,

    (function(){ ... })();
defines and executes kamikaze function. It's a function which dies as soon as its job is completed.

We can use the kamikaze to hide secret_private from all but the functions that we want to have access to it.

Since fn is defined in the kamikaze function, fn can access secret_private.

Since fn is assigned to a global variable, it can be accessed from outside the kamikaze.

When the kamikaze dies, it takes all of its variables with it, except for the ones that are referred to outside of the kamikaze.

temporary disappears because it is referred to only inside the kamikaze.

But, since secret_private is referred to in fn, and fn is a global, secret_private does not disappear, but now only fn can refer to it.

So sceret_private is essentially a private variable of fn.



I'm referring to all my anonymous functions from now on as kamikaze functions. Brilliant.


Kamikaze functions? Sounds dangerous...


Dangerous, maybe, but high affect.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: