javascriptjavascript-objectsiifemodule-pattern

Need help to understand this immediately invoked function example


This is a fragment of code I've found from a tutorial, but I can't understand clearly it's purpose. Here is the example:

app.js

var oojs = (function(oojs){



    return oojs;

}(oojs || {}));

The first part I'm confused is why it is called with the same parameter as it's argument?
The second doubt is why if there is no "oojs" should call the function with an object literal as parameter? Is this necessary?
Finally why it should return the same as it's function name (oojs).


Maybe it's a way to create an object, but if someone could help me the need of this I will really appreciate.


Solution

  • This is just scoping rules in JavaScript. Whenever a new function is created, a new variable scope is created. The parameter name oojs is indeed the same identifier as the outside parameter oojs but it's more local.

    Here is a simplified example

    function foo(x){
        console.log(x + 2); 
    }
    var x = 3; // this is a different x, it belongs to the outer scope, and not the function
    foo(x); // logs 5, since x is passed to the function, then x + 2 is logged
    

    In this code example, the idea is to only change oojs if it doesn't exist, and then set it to the return value of the immediately invoked function expression. It's similar to a composing module pattern. Personally, I find the syntax rather confusing to read when a lot of lines are involved.