uniqueID = (function() {  // The call object of this function holds our value
    var id = 0;           // This is the private persistent value
    // The outer function returns a nested function that has access
    // to the persistent value.  It is this nested function we're storing
    // in the variable uniqueID above.
    return function() { return id++; };  // Return and increment
})(); // Invoke the outer function after defining it.

解决方案 »

  1.   

    (function(){
        alert("囧");
    })();类似:
    alert((1).toString() + 1);因为:
    1.toString()为错误的语法,“.”有歧义同样:
    function{}()();
    后面的括号也有歧义。
      

  2.   

    英文注释写滴很明白,俺汉化了一下,凑合 L@_@K这么写达到了隐藏 id 的作用,即将 id 私有化,
    只能通过外部方法 uniqueID() 的形式访问,
    每次调用 uniqueID(),id 都会自增 1。<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
     <HEAD>
      <TITLE> New Document </TITLE>
      <META NAME="Generator" CONTENT="EditPlus">
      <META NAME="Author" CONTENT="">
      <META NAME="Keywords" CONTENT="">
      <META NAME="Description" CONTENT="">
     </HEAD> <BODY>
      <SCRIPT LANGUAGE="JavaScript">
      <!--
    var uniqueID = (function() {
        // The call object of this function holds our value.
        // 这个函数的调用对象持有我们的值。
        /*
           This is the private persistent value.
           这是一个私有的持久值。
           The outer function returns a nested function that has access 
           to the persistent value.  It is this nested function we're storing 
           in the variable uniqueID above. 
           外部函数返回一个可以访问该持久值的嵌套函数。
           我们将这个嵌套函数存储在上面的 uniqueID 变量中。
         */
        var id = 0;
        // Return and increment.
        // 返回并递增。
        return function() { return id++; };  
    })(); // Invoke the outer function after defining it.
        // 最后的括号用于在定义了外部函数后调用该外部函数。// 测试:
    try
    {
        alert(id);
    }
    catch (e)
    {
        alert(e.message); // 'id' 未定义
    }
    alert(uniqueID); // function() { return id++; }
    alert(uniqueID()); // 0
    alert(uniqueID()); // 1
    alert(uniqueID()); // 2
      //-->
      </SCRIPT>
     </BODY>
    </HTML>
      

  3.   

    补充一句,虽然 id 是在外部匿名函数中定义的,
    但是 id 又在内嵌匿名函数中被引用,并返回给外部变量 uniqueID,
    从而 uniqueID 拥有了对于内嵌匿名函数的引用,
    即 uniqueID -> function() { return id++; } -> id;
    由于对 id 的引用始终存在,id 会被保存下来,
    正如注释第一话所写,这个(外部)函数的调用对象持有我们的值。
      

  4.   

    函数声明方法: function fun(){}匿名函数(即去掉函数名): function(){} 
    此类用法一般用于事件,比如 window.onload=function(){ .... } 或者 .onclick之类的事件也可以这样用函数的调用,呵呵,当然就是函数名加括号  fun(); 了,那匿名函数的调用就是:
    声明一个匿名函数 function(){} 同时调用它,这样就成了这 function(){}(); 当然,在声明的同时,加个括号,只是优先级的调整而已,所以就成了 (function(){ 代码; })();
      

  5.   

    divs = document.getElementsByTagName("div");
    for(var i=0;i<divs.length;i++)
    {
       divs[i].onclick =function(i){
    return function(){
    alert(i);
    };
       }(i);
    }=====================
    首先onclick 赋予了function(i)这个函数,函数内容
    return function(){
    alert(i);
    };function(i){...}(i);相当于声明了这个函数给onclick时间,然后再调用,
    相当于.net中的  className  cn = new className(i);
    也就所谓的必包。可以搜索下相关的文章看看
      

  6.   

    对于新手疑惑的地方可能有如下几处:
    1.匿名函数的用法
    就是函数定义后理解执行然后销毁.典型的用法有两种
    var varName=function(n){
        return n;
    }(1);
    alert(varName);var varName=(function(n){
         return n;
    })(2);
    alert(varName);2.uniqueID的值究竟是什么
    uniqueID的值匿名函数的执行结果,在本例中uniqueID是一个函数3.必包
    网上很多不罗素了
    uniqueID = (function() {  
        var id = 0;
        return function() { return id++; }; 
    })();alert(uniqueID);
    alert(uniqueID());
    alert(uniqueID());
    alert(uniqueID());
      

  7.   


    此函数的第二个步骤不甚明白:是将2赋给(function(n){return n;})?,赋给这个整体后又是什么样的呢?
    赐教...
      

  8.   

    回24楼,是用2做为参数执行前面的function.
      

  9.   


    <script type="text/javascript">
    function closure(name){
    var realname = name;
    // 返回一个匿名函数的引用
    return function(){
    // 闭包可以控制外域,但是对外封闭
    alert(realname);
    }
    }
    var test1 = closure("yudylaw");// 给匿名函数取名,等待调用
    var test2 = closure("刘玉");

    /**********诡异的闭包***********/

    function closure2(){
    for(var i=0;i<5;i++){
    (function(j){
    window.setTimeout(function(){alert(j);},3000);// 循环结束后异步调用
    })(i);
    }
    }
     // ()(i); // () 函数名,优先级吧(i)参数 
    /*使用闭包注意内存的释放
      闭包可以减少代码量,但是在外部环境未知的情况下,出现异常,维护起来太困难
    */
     </script>书上的一段例子
    <input type="button" value="闭包测试test1" onclick="test1();"><br>
    <input type="button" value="闭包测试test2" onclick="test2();">
    <input type="button" value="闭包测试closure2" onclick="closure2();">
      

  10.   

    谁有<王者归来>,我下的这个不全,[email protected],有的发给我一份,谢谢。
      

  11.   

    (function() {
    var g = 0, r = navigator.userAgent.toLowerCase(), x = function(e) {
    return e.test(r)
    }, l = document.compatMode == "CSS1Compat", z = x(/opera/), i = x(/chrome/), s = x(/webkit/), v = !i
    && x(/safari/), b = v && x(/version\/3/), A = v && x(/version\/4/), q = !z
    && x(/msie/), p = q && x(/msie 7/), o = q && x(/msie 8/), n = !s
    && x(/gecko/), c = n && x(/rv:1\.9/), t = q && !l, y = x(/windows|win32/), k = x(/macintosh|mac os x/), j = x(/adobeair/), m = x(/linux/), d = /^https/i
    .test(window.location.protocol);
    if (q && !p) {
    try {
    document.execCommand("BackgroundImageCache", false, true)
    } catch (u) {
    }
    }
    Ext.apply(Ext, {
    isStrict : l,
    isSecure : d,
    isReady : false,
    enableGarbageCollector : true,
    enableListenerCollection : false,
    applyIf : function(B, C) {//if condition b is empty. use condition c
    if (B) {
    for (var e in C) {
    if (Ext.isEmpty(B[e])) {
    B[e] = C[e]
    }
    }
    }
    return B
    },
    id : function(e, B) {//complex logic
    return (e = Ext.getDom(e) || {}).id = e.id
    || (B || "ext-gen") + (++g)//operator "||" has precedence over operator "+"
    },
    extend : function() {
    var B = function(D) {
    for (var C in D) {
    this[C] = D[C]
    }
    };
    var e = Object.prototype.constructor;
    return function(I, E, H) {
    if (Ext.isObject(E)) {
    H = E;
    E = I;
    I = H.constructor != e
    ? H.constructor
    : function() {
    E.apply(this, arguments)
    }
    }
    var D = function() {
    }, G, C = E.prototype;
    D.prototype = C;
    G = I.prototype = new D();//I do not think propotype is a legal name
    G.constructor = I;
    I.superclass = C;
    if (C.constructor == e) {
    C.constructor = E
    }
    I.override = function(F) {
    Ext.override(I, F)
    };
    G.superclass = G.supr = (function() {
    return C
    });
    G.override = B;
    Ext.override(I, H);
    I.extend = function(F) {
    Ext.extend(I, F)
    };
    return I
    }
    }(),
    override : function(e, C) {
    if (C) {
    var B = e.prototype;
    Ext.apply(B, C);//this case accomplish its mission 
    if (Ext.isIE && C.toString != e.toString) {//check to make sure
    B.toString = C.toString
    }
    }
    },
    namespace : function() {
    var B, e;
    Ext.each(arguments, function(C) {
    e = C.split(".");
    B = window[e[0]] = window[e[0]] || {};
    Ext.each(e.slice(1), function(D) {//D mean?
    B = B[D] = B[D] || {}
    })
    });
    return B
    },
    urlEncode : function(F, E) {
    var B = [], C, D = encodeURIComponent;
    for (C in F) {
    Ext.each(F[C] || C, function(G, e) {
    B.push("&", D(C), "=", G != C ? D(G) : "")
    })
    }
    if (!E) {
    B.shift();
    E = ""
    }
    return E + B.join("")
    },
    urlDecode : function(C, B) {
    var F = {}, E = C.split("&"), G = decodeURIComponent, e, D;
    Ext.each(E, function(H) {
    H = H.split("=");
    e = G(H[0]);
    D = G(H[1]);
    F[e] = B || !F[e] ? D : [].concat(F[e])
    .concat(D)
    });
    return F
    },
    toArray : function() {
    return q ? function(e, D, B, C) {
    C = [];
    Ext.each(e, function(E) {
    C.push(E)
    });
    return C.slice(D || 0, B || C.length)
    } : function(e, C, B) {
    return Array.prototype.slice.call(e, C || 0, B
    || e.length)
    //调用一个对象的一个方法,以另一个对象替换当前对象call([thisObj[,arg1[, arg2[,   [,.argN]]]]])
    //call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
    //如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj
    }
    }(),
    each : function(E, D, C) {
    //each( Array/NodeList/Mixed array, Function fn, Object scope ) : void 
    //Iterates an array calling the passed function with each item, stopping if your function returns false.
    //If the passed array is not really an array, your function 
    //is called once with it. The supplied function is called with (Object item, Number index, Array allItems).
    if (Ext.isEmpty(E, true)) {
    return
    }
    if (typeof E.length == "undefined" || typeof E == "string") {
    E = [E]//mean? [E] is an array. if E = {} then is object
    }
    for (var B = 0, e = E.length; B < e; B++) {
    if (D.call(C || E[B], E[B], B, E) === false) {//exact meaning????
    //===除了不进行类型转换,并且类型必须相同以外,这些运算符与相等运算符的作用是一样的
    return B
    }
    }
    },
    getDom : function(e) {
    if (!e || !document) {
    return null
    }
    return e.dom ? e.dom : (typeof e == "string" ? document
    .getElementById(e) : e)
    },
    getBody : function() {
    return Ext.get(document.body || document.documentElement)
    },
    removeNode : q ? function() {
    var e;
    return function(B) {
    if (B && B.tagName != "BODY") {
    e = e || document.createElement("div");
    e.appendChild(B);
    e.innerHTML = ""
    }
    }
    }() : function(e) {
    if (e && e.parentNode && e.tagName != "BODY") {
    e.parentNode.removeChild(e)
    }
    },
    isEmpty : function(B, e) {
    return B === null || B === undefined
    || ((Ext.isArray(B) && !B.length))
    || (!e ? B === "" : false)
    },
    isArray : function(e) {
    return Object.prototype.toString.apply(e) === "[object Array]"
    },
    isObject : function(e) {
    return e && typeof e == "object"
    },
    isPrimitive : function(e) {
    var B = typeof e;
    return B == "string" || B == "number" || B == "boolean"
    },
    isFunction : function(e) {
    return typeof e == "function"
    },
    isOpera : z,
    isWebKit : s,
    isChrome : i,
    isSafari : v,
    isSafari3 : b,
    isSafari4 : A,
    isSafari2 : v && !b,
    isIE : q,
    isIE6 : q && !p && !o,
    isIE7 : p,
    isIE8 : o,
    isGecko : n,
    isGecko2 : n && !c,
    isGecko3 : c,
    isBorderBox : t,
    isLinux : m,
    isWindows : y,
    isMac : k,
    isAir : j
    });
    Ext.ns = Ext.namespace
    })();
      

  12.   

    这是extjs3.0中ext.js中的一段代码!这样的闭包超级恼人!究竟是什么作用,请大侠点拨!
      

  13.   

    定义函数的时候结尾加()是直接调用函数的一种方法。很多时候用在匿名函数
    比如
    (function (a){
    alert(a);
    })('b');相当于
    function c(a){
    alert(a);
    }
    c('b');也可以这样
    (function c(a){
    alert(a);
    })('b');一般要将整个函数体用括号括起来,有的浏览器的js一定要括号括起来才有作用。
    =========lz的函数返回的是一个函数,并且函数里面引用到了返回函数时产生的一个变量引用....。这样子会产生一个所谓的闭包。这是另外一个问题了。
      

  14.   

    (function (a){
    alert(a);
    })('b');相当于
    function c(a){
    alert(a);
    }
    c('b');也可以这样
    (function c(a){
    alert(a);
    })('b'); 
      

  15.   

    其实我感觉网上有写讨论js闭包有很多在那长篇的说,
    很多都是简单问题复杂化,很多都是费话,把有些对js 不是很熟悉的人弄得晕头转向的.
      

  16.   

    上面: function(){alert("匿名函数");}();还要在function前面加"!"才能直接调用吧,即: !function(){alert("匿名函数");}();