함수 표현식
- 함수는 1급 객체 : 변수에 할당이 가능하며 매개변수로 전달도 가능 그리고 return 값으로도 사용이 가능하다 <br>
// 인자의 제곱을 계산하는 익명함수
const square = function(x) {return x*x}
// 이름을 사용하는 함수 표현식 , recursion에 유용한 방식
const f = function fact(x) {if (x<=1) return 1; else return x*fact(x-1)}
// 함수 표현식은 다른 함수의 인자로 사용될수 있다
[3,2,1].sort(function (a,b) {return a-b});
// 함수 표현식을 정의하는 즉시 호출하는 경우
let tensquared = (function(x) {return x*x}; (10));
자바 스크립트 함수를 호출하는 방식
- 함수로 호출 (C나 JAVA에서 사용하는것과 같은 방식) <br>
- method로 호출
function getGreeting() { return ("Hello World");}
const obj = {
hello : getGreeting, //method로 외부 함수를 이용하는방법
sum : function(x,y) { return x+y;}, //함수 표현식을 사용
fact(n){ //method 단축 문법
let result = 1;
for(let x = 2;x<=n;x++) result *= x;
return result;
}
}
console.log(obj.hello() , obj.sum(10,20) , obj.fact(10)) //method 호출
console.log(Object.keys(obj)); // obj 객체의 키를 조회
- this와 화살표 함수(Arrow Function) <br>
const obj = {
i : 10,
b : () => console.log(this.i , this), //화살표 함수는 스스로의 this를 가질수없다 즉 , method로 사용 할 수 없음!!
c() { console.log(this.i , this)},
};
obj.b(); //undefined{}
obj.c(); //10 {i:10 , b:[Function :b], c: [Function :c]}
//인자가 배열일 경우 배열전체를 받거나 배열의 원소를 각각 받을 수 있다
function arrayAdd1 (v1 , v2){
return[v1[0] + v2[0] , v1[1] + v2[1]];
}
function arrayAdd2([x1 , y1] , [x2 , y2]){
return [x1 + x2 , y1 + y2];
}
arrayAdd1([1,2] , [3,4]); //[4,6]
arrayAdd2([1,2] , [3,4]); //[4,6]
//객체 인자를 받을때는 property 이름을 기준으로 분해 할수 있다
function vectorMultiply({x,y} , scalar){
return {X : x *scalar , Y:y*scalar};
}
vectorMultiply({x:1 , y:2},2); //{X:2 , Y:4}
- 함수를 변수나 , 객체의 property , 배열의 원소등에 할당할 수 있다
function add(x,y) { return x+y}
function multiply(x,y) { return x*y}
function operate(operator , operand1 , operand2){
return operator(operand1 , operand2);
}
let i = operate(add , operate(add , 2,3) , operate(multiply(4,5)) // 25 , (2+3) + (4*5)
const operators = {
add : (x,y) => {x+y},
pow : Math.pow
}
function operate2(operation , operand1 , operand2){
return operators[operation](operand1 , operand2);
}
operate2("add" , "hello" , operate2("add" , "" , "world")) //"hello world"
operate2("pow" , 10,2) //100
- 함수는 객체이므로 , property를 가질수 있다 <br>
- static 변수들을 함수 property에 등록하고 사용하면 편리하다 <br>
uniqueInteger.counter = 0;
function uniqueInteger(){ return uniqueInteger.counter++;}
uniqueInteger(); //0
uniqueInteger(); //1
//이전 함수의 실행 결과들을 캐싱하는 예
function factorial(n){
if(Number.isInteger(n) && n>0){ //양의 정수만 사용
if(!(n in factorial)){ //캐시된 결과가 없다면
factorial[n] = n*factorial(n-1);//계산하고 캐시에 저장
return factorial[n]; //캐시된 결과를 반환
} else return NaN; //입력이 잘못된 경우
}
}
factorial[1] = 1; //캐시를 초기화
factorial(6); //720
factorial[5]; //120 이값은 이미 캐시에 존재하는 값