0

When wrapping code inside a function, i pass jQuery at the bottom and the $ sign as a parameter to add it to the functions scope.

(function(window,$,undefined){


}(window, jQuery));

How can i do that with my own Objects?

I load my object in a separate script tag

function MyObj (){
}

So i guessed that all it takes is

(function(window,$,MyObj){

    var myObj = new MyObj();

}(window, jQuery, MyObj));

But MyObj is undefined. I know i could wrap MyObj inside an IFI - but MyObj also needs some json-data that isnt there on page load...

Thanks for your help.

  • 2
    As long as the separate script tag is BEFORE that IIFE that you've shown, then you shouldn't see that MyObj is undefined. – Adam Sep 01 '14 at 17:55
  • 1
    ... and "MyObj" must be declared at the global level - if the other script has all its code wrapped in a function like that, then "MyObj" won't be global. – Pointy Sep 01 '14 at 17:57
  • what's the advantage of re-defining a variable that can be reached by the same name from inside the function? – dandavis Sep 01 '14 at 17:59
  • @dandavis: See [here](http://stackoverflow.com/q/2716069/1048572) – Bergi Sep 01 '14 at 18:04
  • If that were really the case, the function would not be `undefined`. – Pointy Sep 01 '14 at 18:08
  • all good. it works now. sorry for stealing your time. – user3144851 Sep 01 '14 at 18:11
  • if this is supposed to be being done for performance, i doubt today's browsers will benefit. if performance is the only reason to do this, then it's probably not worth doing. – dandavis Sep 01 '14 at 21:28

0 Answers0