JS/JavaScript

[JS] 13. Closure

밍글링글링 2017. 8. 28.
728x90

13_Closure.html

<script>
//Closures are an extension of the concept of scope. With closures, 
//functions have access to variables that were available in the scope 
//where the function was created.

//Each function executed within the loop will reference
//the last value stored in i (5).
//This won't behave as we want it to - every 100 milliseconds, 5 will alert
for(var i=0; i<5; i++){
    setTimeout(function(){console.log(i);}, 100);
}

//Using a closure to create a new private scope
//fix: “close” the value of i inside createFunction, so it won't change
var createFunction = function(i){
    return function(){
        console.log(i);
    };
};
for(var i=0; i<5; i++){
    setTimeout(createFunction(i), 100);
}



//Using a closure to access inner and outer object instances simultaneously.
var outerObj = {
        outerFunction: function(){
            //Provide a reference to outerObj through innerFunction's closure
            var self = this;
            var innerObj = {
                    myName: "inner",
                    innerFunction: function(){
                        console.log(self.myName, this.myName); //"outer inner"
                    }
            };
            innerObj.innerFunction(); //"outer inner"
            console.log(this.myName); //"outer"
        }
};
outerObj.outerFunction();

//Let's manipulate "this" with a basic example.
var user = "johnsmith";
var module = {
        getUser: function(){
            return this.user;
        },
        user: "janedoe"
};
//module.getUser() is called where "module" is "this"
//and "module.user" is returned. 
//janedoe
console.log(module.getUser());

//let's now store a reference in the global version of "this"
//getUser() called, "this" is global, "user" is returned
//johnsmith
var getUser = module.getUser;
console.log(getUser());

//store a ref with "module" bound as "this"
var boundGetUser = getUser.bind(module);
//boundGetUser() called, "module" is "this" again, "module.user" returned.
//janedoe
console.log(boundGetUser());
</script>
 

728x90

'JS > JavaScript' 카테고리의 다른 글

[JSP] 파일업로드 로딩 화면 샘플 소스 DEMO  (0) 2018.04.02
[JQuery] [ajax] 04. ajaxMethod  (0) 2017.08.28
[JS] 12. scope  (0) 2017.08.28
[JS] 11. This  (0) 2017.08.28
[JS] 10. TypeOf  (0) 2017.08.28

댓글