ychow / Blog

My Technology Blog
MIT License
32 stars 5 forks source link

说说闭包 #6

Open ychow opened 9 years ago

ychow commented 9 years ago

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

   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"