views:

39

answers:

2

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
})();
+3  A: 

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:

CMS
so when would you want, or need, to delete something from the global object?
Russ Bradberry
@Russ: Well, a common practice is to simply set them to `null`.
CMS
A: 

Semantically nothing. However, the first example you can have "private" functions that can make your code more readable.

Take this example:

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

Cleaner code results in the hands of a good developer

Jonathan S.