자바스크립트에서 함수는 일급 객체(First-Class Object)라고 한다.
일급객체(First-class Object)란
다른 객체들에 일반적으로 적용 가능한 연산을 모두 지원하는 객체를 가리킨다.
즉, 다른 객체들과 일반적으로 같다라고 생각하면 된다.
함수는 변수에 할당할 수 있다.
//변수 선언부 //변수에 함수 할당
const sayHello = function() {
console.log('Hello!');
};
//변수명으로 어디서든 호출 가능
sayHello(); // "Hello!" 출력
//다른 프로그래밍 언어로는 이렇게 사용 못한다고 함 신기
함수는 다른 함수에 인자로 전달될 수 있다.
콜백(callback)이나 고차 함수(higher-order function)를 작성하는 데 사용됨💡 콜백 함수와 고차 함수(Higher-Order Function)
콜백 함수: 어떠한 함수의 매개변수로 쓰이는 함수고차 함수: 함수를 인자로 받거나, 함수를 출력으로 반환하는 함수
- 함수를 다루는 함수
- 따라서 콜백함수는 고차함수의 한 종류 라고도 할 수 있음
function callFunction(func) { //함수를 인자로 받음
func(); // 매개변수로 받은 변수가 함수!
}
const sayHello = function() {
console.log('Hello!');
};
//callFunction 함수의 매개변수로 sayHello 함수를 던짐
callFunction(sayHello); // "Hello!" 출력
함수는 다른 함수에서 반환될 수 있다.
함수 팩토리(factory)나 클로저(closure)를 작성하는 데 사용됨function createAdder(num) {
return function (x) { //함수의 리턴이 함수 => 고차함수
return x + num
};
};
//✅ createAdder에 매개변수로 5를 주고 실행한 결과를 addFive에 할당
const addFive = createAdder(5);
//✅ => 따라서 addFive에 할당된 함수는 다음과 같음
const addFive = function (x) {
return x + 5
};
//✅ addFive에 매개변수로 10을 주면?
console.log(addFive(10)); // 15
// function (10) {
// return 10 + 5
// };
함수는 객체의 프로퍼티(속성)로 할당될 수 있다.
// 객체는 키-밸류-페어
const person = {
name: 'John',
//키 //밸류 //객체 프로퍼티로 함수 할당
sayHello: function() {
console.log(`Hello, my name is ${this.name}`);
//✅ this 사용
//중괄호{} 안 스코프에서의 this는 항상 자기 자신(객체)을 가리키므로
//person객체의 name에 접근하려면 this.name을 사용하면 됨
}
};
//객체의 메소드로 함수 호출 가능
person.sayHello(); // "Hello, my name is John" 출력
const person = {
name: 'John',
sayHello: () => {
console.log(`Hello, my name is ${this.name}`);
//❌ 화살표 함수는 this를 바인딩하지 않기 때문에 undefined 출력됨
}
};
person.sayHello(); // "Hello, my name is undefined" 출력
따라서 객체의 프로퍼티로 함수를 할당할 때,
- 화살표 함수는 this를 바인딩하지 않기 때문에
- 화살표 함수를 사용하지 말고 일반 함수를 사용하자!
const myArray = [function(){}, function(){}]
함수는 배열의 요소로 할당될 수 있다.
//함수를 요소로 가지는 배열
const myArray = [
function(a, b) { // myArray의 0번째 요소 //myArray[0]
return a + b;
},
function(a, b) { // myArray의 1번째 요소 //myArray[1]
return a - b;
}
];
//배열의 요소에 접근하기
//arr[인덱스넘버]
//myArray의 0번째 요소에 매개변수로 5, 10 주기
console.log(myArray[0](5, 10)); // 15 출력
//myArray의 1번째 요소에 매개변수로 10, 5 주기
console.log(myArray[1](10, 5)); // 5 출력
함수가 일급 객체로 취급되기 때문에,
함수를 일급 객체로 다룰 수 있다는 것은,
//고차 함수로 함수 리턴
function multiplyBy(num) {
return function(x) {
return x * num;
}
}
//간단한 함수
function add(x, y) {
return x + y;
}
//1. 변수에 함수 할당하면,
const multiplyByTwo = multiplyBy(2);
//아래랑 같은 의미
const multiplyByTwo = function(x) {
return x * 2;
}
//2. 변수에 함수 할당하면,
const multiplyByThree = multiplyBy(3);
//아래랑 같은 의미
const multiplyByThree = function(x) {
return x * 3;
}
//3. result 변수에 add()함수 할당하여 위에서 각 매개변수에 할당한 함수 전달
const result = add(multiplyByTwo(5), multiplyByThree(10)); // 🔥40 출력🔥
//3-1. 아래랑 같은 의미
const result = function add(multiplyByTwo(5), multiplyByThree(10)) {
return multiplyByTwo(5) + multiplyByThree(10);
}
//3-1-1. multiplyByTwo(5) 는 아래와 같은 의미
function(5) {
return 5 * 2; //🔥10
}
//3-1-2. multiplyByThree(10) 는 아래와 같은 의미
function(10) {
return 10 * 3; //🔥30
}
//3-2. 아래랑 같은 의미
const result = function add(10, 30) {
return 10 + 30; // 🔥40 출력🔥
}
이처럼 함수가 일급 객체로 취급되는 것은,