js闭包

uniqueID=function(){
if(!arguments.callee.id) arguments.callee.id=0;
return arguments.callee.id++;
}
uniqueID();
uniqueID();
uniqueID();
alert(uniqueID.id);
uniqueID.id=0;//设置uniqueID属性id为0.
alert(uniqueID.id);//0

实现一个函数,使用自己的属性来存储雍久值。但在函数外部,可以重设id为0.

uniqueID=(function(){
var id=0;
return function(){return id++;}
}
)();
uniqueID();
uniqueID();//1
uniqueID.id=0;
uniqueID();
uniqueID();//3

同样设置属性id为0.但是没有用。

更复杂的闭包例子:

function makeProperty(o, name, predicate) { 
    var value;  // This is the property value 

    o["get" + name] = function() { return value; }; 
 
    
    o["set" + name] = function(v) { 
        if (predicate && !predicate(v)) 
            throw "set" + name + ": invalid value " + v; 
        else 
            value = v; 
    }; 
}
var o = {};
makeProperty(o, "Name", function(x) { return typeof x == 
"string"; }); 
//o.setName("Frank");  // Set the property value 
//alert(o.getName());  // Get the property value "Frank"
o.setName(0);   // Set the property value 
alert(o.getName());//  "setName: invalid value 0"    

以上,o.getName=function() { return value; };

o.setName=function(v);

o.predicate=function(x) { return typeof x == "string";}

调用就可以直接o.setName(V);o.getName()了。

更复杂的闭包列子

 

function inspect(inspector, title) { 
    var expression, result; 
    if ("ignore" in arguments.callee) return;  
    while(true) { 
        // Figure out how to prompt the user 
        var message = ""; 
        // If we were given a title, display that first 
        if (title) message = title + "\n"; 
        if (expression) message += "\n" + expression + " ==> " 
+ result + "\n"; 
        else expression = ""; 
        // We always display at least a basic prompt: 
        message += "Enter an expression to evaluate:";         
        expression = prompt(message, expression);         
        if (!expression) return; 
        result = inspector(expression); 
    } 
}
function factorial(n) { 
    // Create a closure for this function 
    var inspector = function($) { return eval($); } 
    inspect(inspector, "Entering factorial()"); 
 
    var result = 1; 
    while(n > 1) { 
        result = result * n; 
        n--; 
        inspect(inspector, "factorial() loop"); 
    } 
 
    inspect(inspector, "Exiting factorial()"); 
    return result; 
} 
factorial(5);

 

inspect可以中断来检测函数factorial中,n和result的结果。

闭包似乎就是只可以通过内部函数来调用访问变量、参数的意思。

 

posted on 2012-07-13 15:39  rorodo  阅读(215)  评论(0)    收藏  举报