zoukankan      html  css  js  c++  java
  • (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);
  • 相关阅读:
    Reducing File Size
    程序设计中的命名
    代码进阶
    如何显示当前Mipmap级别?
    何时使用泛型集合
    Using Mono DLLs in a Unity Project
    lock关键字
    VSS/RSS/PSS/USS
    AssetBundle依赖
    WWW.LoadFromCacheOrDownload
  • 原文地址:https://www.cnblogs.com/jasenkin/p/javascript_self_call_namespace.html
Copyright © 2011-2022 走看看