2015년 3월 1일 일요일

클로저 심플예제

클로저는 외부 변수의 값을 복사하지 않고 참조한다.


1.자바스크립트는 현재함수의 외부에 있는 변수를 가져와서 사용할수도 있다.


----------------------------------------


function makeSandwich(){
var magicIngredient="peanut butter";
function make(filling){
return magicIngredient + "and "+ filling;
}
return make;
}
var f=makeSandwich();


console.log(f("hehe"));
console.log(f("jelly"));
console.log(f("bananas"));


--------------------------------------


2.함수는 외부함수가 무언가ㄴ를 리턴한 이후에도 외부함수에 선언도니 변수를 참조할수 있다. 즉 함수내의 변수를 지속적으로 고정,공유할수 있다.


function makeSandwich(magicIngredient){
return function (filling){
return magicIngredient + " and "+ filling;
}
return make;
}
var f=makeSandwich("ham");


console.log(f("hehe"));
console.log(f("jelly"));


-----------------------------------


3.클로져는 외부 변수의 값을 변경할수 있다.


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

}
var b=box();
b.type();
b.set("76.1");
console.log(b.get());
console.log(b.type());

0 comments:

댓글 쓰기