0

Q1: How can I load the myApp object from inside the anonymous function into the DOM ready function. I know one way to pass the object is using the window.myApp = myApp; inside the anonymous function but this exposes the myApp Object as a global object.

$(function(){
    //Load myApp inside here
});

(function(){
   var myApp = {
     //with properties inside
   }
}());

Q2:Also, I've seen the following brackets inside and brackets outside. What do they do?

(function(){
   var myApp = {
     //with properties inside
   }
}(brackets inside))(brackets outside);

Q3: I know its not possible but is there a hack/trick to load the anonymous function after DOM loads?

Vish
  • 383
  • 2
  • 8
  • 25
  • 1
    Couldn't you place `myApp` into DOM ready itself? – Rahil Wazir Feb 09 '14 at 19:56
  • Having the `myWholeApp` singleton as a global object is not a problem. – Bergi Feb 09 '14 at 21:54
  • I could do that but I am working to isolate all the core properties and methods inside the anonymous functions, and only use the DOM ready to manipulate the DOM elements. – Vish Feb 09 '14 at 21:54

1 Answers1

1

May be like this:

(function () {
    var myApp = {
        //with properties inside
    }
    $(function () {
        // document is ready AND myApp is accessible
        myApp.init();
    });
}());

Regarding 2nd part of your question: placing invocation inside or outside the parenthesis does not make a difference. Some coders prefer one variant over the other. Details here.

(function(){ /* do something */ })(); // invocation outside parenthesis
(function(){ /* do something */ }()); // invocation inside parenthesis

In case you are asking what does ()() do; it invokes a function that returns a function and invokes the returned function. Consider this example and its output:

(function () {
    console.log("anonymous outer function");
    return function () {
        console.log("anonymous inner function");
    }
})()();

// output:
// anonymous outer function
// anonymous inner function 
Salman A
  • 262,204
  • 82
  • 430
  • 521