1

In this example code:

    (function(){
           var obj = function() {

           };

           obj.prototype.hello = function(){
                 console.log('Hello World!');
           };
    })();

I see a lot of libraries doing this. Why is wrapping your code in an Immediately Invoked Function Expression (IIFE) a good practice? And how do I access this object outside, like jquery does?

Because if I do something like this:

   var test = new obj();

The browser displays that obj is undefined.

JAAulde
  • 19,250
  • 5
  • 52
  • 63
and-k
  • 537
  • 1
  • 8
  • 16

1 Answers1

7

To avoid polluting outer scope. You're sure no variables are going to "get out" of it. But yes, you do need to export it. Either using window.obj = obj; from inside (to make it global) or return it :

var obj = (function() {
  var obj = function() {};
  obj.prototype.sayHello = function() {}; 
  return obj;
})();
Ven
  • 19,015
  • 2
  • 41
  • 61
  • Thank you, but a lot of javascript libraries export the object without assign the IIFE to a variable. How they do it? – and-k Aug 22 '13 at 18:53
  • The first solution of my "either" : `window.jQuery = jQuery`, for example – Ven Aug 22 '13 at 18:54