Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

说说闭包 #6

Open
ychow opened this issue Mar 12, 2015 · 0 comments
Open

说说闭包 #6

ychow opened this issue Mar 12, 2015 · 0 comments

Comments

@ychow
Copy link
Owner

ychow commented Mar 12, 2015

其实闭包真没有什么好可怕的。学会它,你只需要理解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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant