Mark Estrada
Mark Estrada

Reputation: 9201

About this Javascript Code Construct

I am currently debugging some code right now but I cant get myself around this concept in javascript.

I have this code construct.
if(!COMPANY)
    COMPANY = {};

COMPANY.Billing = (function(COMPANY){
    //More code
})(COMPANY);

As, i understand, it creates an object called "COMPANY" and then adds a new property called "Billing" but I dont understand the idea of passing the same "COMPANY" into the arguments of the function and at the same time renaming it to "COMPANY" again. What I mean is what is the difference between the code above and the code below.

COMPANY.Billing = (function(COMPANY){
    //More code
})();

My javascript is not that deep so I would like to understand what the code construct above means. This might be some javascript design pattern but I dont know what it is

Upvotes: 0

Views: 55

Answers (1)

elixenide
elixenide

Reputation: 44841

It isn't renaming COMPANY; it's using it. Annotated version of your code:

if(!COMPANY)            // if COMPANY doesn't exist...
    COMPANY = {};       // initialize it to a blank object

COMPANY.Billing =       // initialize a property
    (function(COMPANY){ // this defines a function
        //More code
    })(COMPANY);        // this executes the function with COMPANY as the parameter
// COMPANY.Billing now contains the result of executing the anonymous function

This is called a closure. Example:

foo = (function(x) {
    return ++x;
})(4);

This defines a function, then executes with parameter x = 4. So, it returns ++x, which is 5. Therefore, foo is assigned the value 5.

When you do this:

COMPANY.Billing = (function(COMPANY){
    //More code
})();

You are defining a closure and executing it, but you are passing nothing as a parameter. So, COMPANY is undefined inside the closure.

Upvotes: 1

Related Questions