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

人盡茶涼 提交于 2020-03-06 18:56:50

  (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);

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!