Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self-executing functions [duplicate]

Tags:

javascript

Possible Duplicate:
Difference between (function(){})(); and function(){}();

I am trying to understand a few of the features of JavaScript a little better. In The Definitive JavaScript it says that self-executing functions should have brackets round them like so:

var obj = (function() {
    var value = 0;

    return {
        increment: function(inc) {
            value += typeof inc === "number" ? inc : 1;
        },
        getValue: function() {
            return value;
        }
    }
})();

but in JavaScript - The Good Parts where this example is taken from, it has the above self-executing function without the brackets round, like so:

var obj = function() {
    var value = 0;

    return {
        increment: function(inc) {
            value += typeof inc === "number" ? inc : 1;
        },
        getValue: function() {
            return value;
        }
    }
}();

Both of these examples work for me, but I wanted to ask if there were any differences in functionality that I should be aware of. I hope this isn't too trivial. I just wanted to be sure.

Thanks a lot.

Edit:

As Rob W has pointed out, there is another thread on the subject. This is an excellent blog regarding this issue that was linked to from the other post.

like image 215
Joe Avatar asked Jun 18 '12 14:06

Joe


1 Answers

There isn't any difference in this case, but only because it's prefixed with:

var obj = ...

Without that, only the first version is correct, because you need the additional parentheses to allow the interpreter to correctly parse the function as a function expression and not as a function declaration.

You would of course only omit var obj if you only want the function to run (i.e. you want its side effects) but it either returns no value, or you don't care what its return value is.

like image 162
Alnitak Avatar answered Oct 13 '22 20:10

Alnitak