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.

4

1 回答 1

6

避免污染外部范围。您确定没有变量会“摆脱”它。但是,是的,您确实需要将其导出。从内部使用window.obj = obj;(使其成为全局)或返回它:

var obj = (function() {
  var obj = function() {};
  obj.prototype.sayHello = function() {}; 
  return obj;
})();
于 2013-08-22T18:46:20.083 回答