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

(function(){

        ......

  }())

 或 

 (function(){   

        ......

  })()

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

例如json2.js

(function () {

    function f(n) {
// Format integers to have at least two digits.
return n < ? '' + n : n;
} if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + ) + '-' +
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);
上一篇:利用 Windows Azure 实现“云优先”


下一篇:HDU2176尼姆博弈