Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain the following JavaScript statement? [duplicate]

Tags:

javascript

People also ask

What are JavaScript statements?

Statements are used in JavaScript to control its program flow. Unlike properties, methods, and events, which are fundamentally tied to the object that owns them, statements are designed to work independently of any JavaScript object.

What are the conditional statements in JavaScript?

In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.


This code is equivalent to:

function Ninja() {
    // nothing here
}

var ninja = new Ninja();

Though in the code you listed, the function/object Ninja is not global scope.

The code (function() {...})(); basically says "take whatever function is contained inside here and execute it immediately". So it's creating an anonymous function and calling it right afterwards.


It's called an Immediately-Invoked Function Expression (or IIFE). It creates a new scope and executes the contents immediately. There are many uses for it; the one I use the most is when the this keyword would change meaning, e.g. in

var someClass = function() {
    this.property = something;
    this.update = (function(obj) {
        function() {
            $('.el').each(function() {
                $(this).html( obj.property );
            });
        };
    )(this);
};

While I want to refer to this.property inside the $('.el').each(), this changes meaning within that scope and refers to the current DOM element that is being looped through with .each(). So by passing this as a parameter into the IIFE (and calling that parameter obj) I can use obj.property to refer to what is this.property when outside the scope of $('.el').each( ..., function() { ... });.

Let me know if that makes sense or if you have any questions :)


Why is the function declaration encapsulated in '('s and also why is there a '();' in the end

Its declaring and executing the function at the same time.

You may see: Named function expressions demystified - by Juriy "kangax" Zaytsev