5

On some JS code on some sites I see Javascript code such as this:

SomeName.init = (function () {
    // some stuff
})();

I mean, this is not a jQuery plugin code such as this:

(function( $ ){
    $.fn.myPlugin = function() {

    // Do your awesome plugin stuff here

    };
})( jQuery );

Then, what is it? and what is the resulting JS object?

Ken D
  • 5,880
  • 2
  • 36
  • 58
  • I ... not sure what you're asking. Both snippets demonstrate a function that is both declared and executed. Beyond that, they don't seem related. – g.d.d.c Sep 28 '11 at 17:52
  • The 1st one is setting the results of an anonymous function into a variable named "init". And as seen in the 2nd example, the anonymous function is a design-pattern often used in creating PLUG-IN's (or modules) and thus is often called the 'Module Pattern'. – Prisoner ZERO Sep 28 '11 at 17:58
  • [Here's what I found](http://stackoverflow.com/questions/5101638/what-does-this-javascript-code-mean) when I typed your title into the search box. – user113716 Sep 28 '11 at 18:06
  • @Ӫ_._Ӫ I used search before posting my question, but there are really a lot of questions with this title. of course, they are not duplicates of each other but I didn't find the one you shared. – Ken D Sep 28 '11 at 18:09

4 Answers4

8

It's a anonymous function, which doesn't leak variables to the global scope when declaring variables using var.

SomeName.init = (function () {
    return 3.1415;
})();

SomeName.init is a number (3.1415), because () after the anonymous function declaration executes the function. There's no way to obtain the original function, unless defined within the anonymous function:

(function foo(){
    //foo refers to this function
    too = foo;
})();;
//foo is undefined
//too refers to the function, because `too` has been defined without var
Rob W
  • 341,306
  • 83
  • 791
  • 678
2

The Module Pattern. And those two snippets have more in common than you think.

J. Holmes
  • 18,466
  • 5
  • 47
  • 52
1
(function () {
    // some stuff
})()

is a anonymous function that calls itself instantly. It's just a closure around the code inside to stop the variable scope becoming global.

Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
0

Whatever the function returns.

(function() {
    //...
})();

Is used as a way to namespace code, or declare self-executing constructors. The resulting object is whatever that self-executing function returns.

The second snippet doesn't return anything and there is no resulting JS object.

Chad
  • 19,219
  • 4
  • 50
  • 73