Blog icon indicating copy to clipboard operation
Blog copied to clipboard

说说闭包

Open ychow opened this issue 9 years ago • 0 comments

其实闭包真没有什么好可怕的。学会它,你只需要理解3个事实。

  • Javascript允许你引用在当前函数以外定义的变量。
   function test(){
    var sometext="Hello";
    function make(name){
        return sometext+","+name;
    };
    return make("ychow");
};
test();  //"Hello,ychow"
  • 即使外部函数已经返回,当前函数仍然可以引用在外部函数所定义的变量。
function test(){
    var test="helo";
    function make(name){
        return test+','+name;
    };
    return make;
};

var f=test();
f('ychow');     //"helo,ychow"
function make(some){
    function test(who){
        return some+','+who;
    };
    return test;
};
var hehe=make("sand");
hehe("witch");          //"sand,witch"

闭包是JavaScript最优雅、最有表现力的特性之一。JavaScript还提供了更为方便的构建闭包的字面量语法-----函数表达式:

function hehe(test){
    return function(name){
        return test+','+name
    }
};

var f=hehe("hello");
f("ychow");     //"hello,ychow"
  • 闭包也可以更新外部变量的值。

其实,闭包存储的是外部变量的引用,而不是其副本。因此任何具有访问外部变量的闭包,都可以更新。

function ychow(){
    var val=undefined;
    return{
        set: function(newVal){
            val=newVal;
        },
        get: function(){
            return val;
        },
        type: function(){
            return typeof val;
        }
    }
};

var b=ychow();
b.type();      //"undefined"
b.set("haha");    
b.get();       //"haha"
b.type();        //"string"

ychow avatar Mar 12 '15 14:03 ychow