Trying to pass "var app" into a function

- 1 answer

Ad

I was trying to do an uploader application with the help of AJAX. I was doing like here

var app = app || {};

(function(0) {
    // can be used 'app.functionName();'
}(app));

But I don't really understand what it is done here. Could anybody explain me this? :/

Ad

Answer

Ad

Let me explain the function part:

function callMe(param){
    console.log(param);
}

(function callMeNow(param){
    console.log(param);
})({}); // logs [object Object]
callMe({}) // logs [object Object]

As you can see, as soon as callMeNow is defined, it runs first.

Because of this, people can do cool things like:

var app = (function callMeNow(param){ // creates its own scope
    var privateVariable = 21;
    var privateFunc = function(){
        return privateVariable
    };
    param.getSecretNumber = privateFunc
    return param;
})({});

console.log(app.getSecretNumber()) // logs 21
Ad
source: stackoverflow.com
Ad