Search code examples
javascriptunobtrusive-javascript

What is the difference between globally declaring a function and using window.myfunc = myfunc


What is the difference between the following 2 examples of code:

(function(){
    var myFunc = (function(){
        //do something
    })();
    window.myFunc = myFunc;
})();

and

var myFunc = (function(){
    //do something
})();

Solution

  • The two ways are really similar, but there is a small difference on how the myFunc global variable is created.

    In the second way, using the var statement, will create the myFunc variable as a non-deleteable property of the global object, the var statement explicitly sets the internal {DontDelete} attribute , e.g.:

    var myFunc = (function(){
        //do something
    })();
    
    delete window.myFunc; // false
    

    While the first one can be deleted:

    (function(){
        var myFunc = (function(){
            //do something
        })();
        window.myFunc = myFunc;
    })();
    
    //...
    delete window.myFunc; // true
    

    If you try the above in Firebug, both can be deleted, thats because Firebug uses code evaluation (eval) in the console.

    You can check the above example here.

    Recommended article: