- a Function is an instance of the object type.
- a Function behaves like any other object.
- we can store functions in a variable.
- we can pass a function as an argument to another function.
- we can return a function from a function.
=> First-Class Functions
First-Class Functions: passing functions as arguments
var years = [1990, 1965, 1937, 2005, 1998];
function arrayCalc(arr, fn){ //array와 function을 매개변수로 받아온다.
var arrRes =[]; // 새배열생성
for(var i = 0 ; i < arr.length; i++ ){ //배열의 길이만큼 루프
arrRes.push(fn(arr[i])); //새배열에 펑션의 결과를 넣어줌
}
return arrRes; // 값을 리턴
}
function calculateAge(el){ //생년
return 2016-el;
}
function isFullAge(el){ //나이
return el >= 18;
}
function maxHeartRate(el){ //나이
if(el >=18 && el<=81){
return Math.round(206.9 - (0.67 * el));// Math.round() 소수점 계산 출력
}else{
return -1;
}
}
var ages = arrayCalc(years, calculateAge); // arrayCalc에 years 배열과 calculateAge 함수를 매개변수로 넣어준다.
var fullAges = arrayCalc(ages, isFullAge);
var heartRates = arrayCalc(ages, maxHeartRate);
console.log(ages);//[26, 51, 79, 11, 18]
console.log(fullAges);//[true, true, true, false, true]
console.log(heartRates);//[189, 173, 154, -1, 195]
=> this way is much readable and mergeable than create one big function and calculate every elements. (simple technique to make a clean code)
First-Class Functions: functions renturning functions
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');
'javascript' 카테고리의 다른 글
JavaScript/ Closure (0) | 2020.02.24 |
---|---|
JavaScript/ Immediately Invoked Function Expressions [IIFE] (0) | 2020.02.24 |
JavaScript/ Primitives vs Objects (0) | 2020.02.24 |
JavaScript/ Function constructor (0) | 2020.02.24 |
JavaScript/ The 'this' keyword (0) | 2020.02.24 |