4

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?

5
  • 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. Commented Sep 28, 2011 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'. Commented Sep 28, 2011 at 17:58
  • Here's what I found when I typed your title into the search box. Commented Sep 28, 2011 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. Commented Sep 28, 2011 at 18:09
  • This question is similar to: What is the (function() { } )() construct in JavaScript?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 10, 2024 at 7:27

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.