Library in one function

Hi,

I investigated a JS file that represents a library that I’m using and was left speechless of the order and the discipline of the code. Everything was wrapped up under a function that looks like this:

(function(window, document, undefined){
    [...]
}());

I googled why the three parameters are added there and found the answer, although I’m not quite clear what this kind of function is called (it’s not an anonymous function), and why it has a parenthesis at the end. Can someone point me to the right direction so I can read more about this type of function?

I understand that this functions starts automatically, but what I found most intriguing was inside. Inside the function, everything is wrapped up in a object, and inside this object, I found these object literals that look like this:

var my_object {
    version: 1.5,
    modules: {},
    core: function(alternatives) {
        [...a lot of code...]
    }
}

The coder follows prototype, but I still didn’t expect the code to be encapsulated like this.

I need to know:

  1. What is the name/s of coding in this fashion? I’m strictly referring to wrapping functions in an object and that object in the function that I showed further above.

  2. How would this function in this object be called?

var my_object = {
    call_that_function: function(stuff) { //call this function
       this.something = true;
    }
} //end my_object

Thanks in advance.

Hi there @sebastian. This is known as IIFE ( Immediately invoked function expression), and it will execute immediately. In short this may be used to create a closure and not pollute the global scope.
More about it here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

I think you would not be able to call it externally since its an IIFE.

Hope it helps,

Andres

2 Likes

Thanks, I’m reading that article now.

As for calling the function, I’m referring to the functions in the object literal, not the IIFE. The IIFE starts on its own, that much is clear, but the object that it hosts is filled with functions of its own, like the example I showed earlier.

This comes to suggest, as far as I could gather without having a look at the actual code that an instance of that prototype is being created within the IIFE and all the code gets initialised within.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.