(function(){...}())与(function(){...})()

  (function(){

        ......

  }())

 或 

 (function(){   

        ......

  })()

 

 匿名函数自调用,也就是说,定义一个匿名函数,然后马上调用它。 因为这个匿名函数的函数体相当于提供一个匿名的名字空间,这样就不会与用户自定义的JS函数、变量、对象发生冲突了,不失为是一种很好的解决命名空间问题的方法。

 

 例如json2.js

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    ......
}());


例如jquery.js

(function( window, undefined ) {

     .....
  
})(window);

 

posted @ 2013-10-20 18:53  jasen.kin  阅读(697)  评论(1编辑  收藏  举报