Ken D
Ken D

Reputation: 5968

What is this code in Javascript?

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?

Upvotes: 4

Views: 182

Answers (4)

Rich Bradshaw
Rich Bradshaw

Reputation: 72975

(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.

Upvotes: 1

Chad
Chad

Reputation: 19609

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.

Upvotes: 0

J. Holmes
J. Holmes

Reputation: 18546

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

Upvotes: 2

Rob W
Rob W

Reputation: 348992

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

Upvotes: 8

Related Questions