Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 657
Ken D Avatar asked Sep 28 '11 17:09

Ken D


People also ask

What is JavaScript code called?

Most JavaScript programs contain many JavaScript statements. The statements are executed, one by one, in the same order as they are written. JavaScript programs (and JavaScript statements) are often called JavaScript code.

What is this inside a function JavaScript?

The this keyword refers to the object the function belongs to, or the window object if the function belongs to no object. It's used in OOP code, to refer to the class/object the function belongs to For example: function foo() { this. value = 'Hello, world'; this.

What are identifiers in JavaScript?

An identifier is a sequence of characters in the code that identifies a variable, function, or property. In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $ , _ , and digits (0-9), but may not start with a digit.

What is HTML () in JavaScript?

The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element.


2 Answers

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
like image 124
Rob W Avatar answered Sep 29 '22 07:09

Rob W


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

like image 39
J. Holmes Avatar answered Sep 29 '22 06:09

J. Holmes