- 함수 안에서 값을 리턴하는 함수
an inner function has always access to the variables and parameters of its outer function,
even after the outer function has returned.
function retirement(retirementAge){
var a = ' years left until retirement.';
return function(yearOfBirth){
var age = 2016 - yearOfBirth;
console.log((retirementAge-age)+a);
}
}
var retirementUS = retirement(66);
var retirementGermany = retirement(65);
var retirementEU = retirement(67);
retirementUS(1990);
retirement(66)(1990);
// both give us same result
retirementGermany(1990);
retirementEU(1990);
challenge
/* rewirte this with closures
function interviewQuestion(job){
if(job==='designer'){
return function(name){
console.log(name + ', can you please explain what UX design is?');
}
}
else if(job==='teacher'){
return function(name){
console.log(name+', what subject do you teach?');
}
}
else{
return function(name){
console.log('hi,'+name+'! what do you do?');
}
}
}
var teacherQuestion = interviewQuestion('teacher');
var designerQuestion = interviewQuestion('designer');
teacherQuestion('John');
designerQuestion('Jane');
designerQuestion('Mark');
interviewQuestion('teacher')('Mark');
*/
function interviewQuestion(job) {
return function (name) {
if(job==='designer'){
console.log(name + ', can you please explain what UX design is?');
}
else if(job==='teacher'){
console.log(name+', what subject do you teach?');
}
else{
console.log('hi,'+name+'! what do you do?');
}
}
} //-> 위의 함수와 달리 클로저를 이용하면 리턴문을 여러면 반복할 필요가 없다
interviewQuestion('teacher')('john');
'javascript' 카테고리의 다른 글
JavaScript/ prototype & closure exercise (0) | 2020.03.09 |
---|---|
JavaScript/ Bind, Call and Apply (0) | 2020.02.24 |
JavaScript/ Immediately Invoked Function Expressions [IIFE] (0) | 2020.02.24 |
JavaScript/ First-Class Functions (0) | 2020.02.24 |
JavaScript/ Primitives vs Objects (0) | 2020.02.24 |