JS의 함수는 위의 조건을 모두 만족함으로 일급 객체이다.
// 1. 함수는 무명의 리터럴로 생성할 수 있다.
// 2. 함수는 변수에 저장할 수 있다.
// 런타임(할당 단계)에 함수 리터럴이 평가되어 함수 객체가 생성되고 변수에 할당된다.
const increase = function (num) {
return ++num;
};
const decrease = function (num) {
return --num;
};
// 2. 함수는 객체에 저장할 수 있다.
const auxs = { increase, decrease };
// 3. 함수의 매개변수에게 전달할 수 있다.
// 4. 함수의 반환값으로 사용할 수 있다.
function makeCounter(aux) {
let num = 0;
return function () {
num = aux(num);
return num;
};
}
// 3. 함수는 매개변수에게 함수를 전달할 수 있다.
const increaser = makeCounter(auxs.increase);
console.log(increaser()); // 1
console.log(increaser()); // 2
// 3. 함수는 매개변수에게 함수를 전달할 수 있다.
const decreaser = makeCounter(auxs.decrease);
console.log(decreaser()); // -1
console.log(decreaser()); // -2
일급 객체로서 함수가 가지는 가장 큰 특징은 일반 객체와 같이 함수의 매개변수에 전달할 수 있으며, 함수의 반환값으로도 사용할 수 있다.
함수는 객체이기 때문에 프로퍼티를 가질 수 있다. 한번 들여다보자.
function square(number) {
return number * number;
}
console.dir(square);
프로퍼티 어트리뷰트를 한번 확인해보자.
function square(number) {
return number * number;
}
console.log(Object.getOwnPropertyDescriptors(square));
/*
{
length: {value: 1, writable: false, enumerable: false, configurable: true},
name: {value: "square", writable: false, enumerable: false, configurable: true},
arguments: {value: null, writable: false, enumerable: false, configurable: false},
caller: {value: null, writable: false, enumerable: false, configurable: false},
prototype: {value: {...}, writable: true, enumerable: false, configurable: false}
}
*/
// __proto__는 square 함수의 프로퍼티가 아니다.
console.log(Object.getOwnPropertyDescriptor(square, '__proto__')); // undefined
// __proto__는 Object.prototype 객체의 접근자 프로퍼티다.
// square 함수는 Object.prototype 객체로부터 __proto__ 접근자 프로퍼티를 상속받는다.
console.log(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'));
// {get: ƒ, set: ƒ, enumerable: false, configurable: true}
이처럼 arguments, caller, length, name, prototype 프로퍼티는 모두 함수 객체의 데이터 프로퍼티이다. 이는 일반 객체에는 없는 함수 객체 고유의 프로퍼티이다.
하지만 proto는 접근자 프로퍼티이며, 함수 객체 고유의 프로퍼티가 아니라 object.prototype 객체의 프로퍼티를 상속받은 것을 알 수 있으며, 이것은 모든 객체가 상속 받아 사용할 수 있다.