18.1 일급 객체

<aside> 💡 다음 조건을 만족하면 일급 객체라고 한다.

  1. 무명의 리터럴로 생성할 수 있다. 즉, 런타임에 생성이 가능하다.
  2. 변수나 자료구조(객체, 배열 등)에 저장할 수 있다.
  3. 함수의 매개변수에 전달할 수 있다.
  4. 함수의 반환값으로 사용할 수 있다.

</aside>

자바스크립트의 함수는 위 조건을 모두 만족하므로 일급 객체다.

// 1. 함수는 무명의 리터럴로 생성할 수 있다.
// 2. 함수는 변수에 저장할 수 있다.
// 런타임(할당 단계)에 함수 리터럴이 평가되어 객체가 생성되고 변수에 할당된다.
const increase = function (num) {
	return ++num;
}

// 2. 함수는 객체에 저장할 수 있다.
const auxs = { increase }';

// 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

18.2 함수 객체의 프로퍼티

함수는 객체다.

함수도 프로퍼티를 가질 수 있다. getOwnPropertyDescriptors 메서드로 확인할 수 있다.

  1. arguments 프로퍼티

    arguments 프로퍼티 값은 arguments 객체다.

    function multiply(x, y) {
    	console.log(arguments);
    	return x * y;
    }
    
    console.log(multiply()); // NaN
    console.log(multiply(1)); // NaN
    console.log(multiply(1, 2)); // 2
    console.log(multiply(1, 2, 3)); // 2
    

    Untitled

    arguments 객체는 매개변수 개수를 확정할 수 없는 가변 인자 함수를 구현할 때 유용하다.

    function sum() {
    	let res = 0;
    	
    	// arguments 객체는 length 프로퍼티가 있는 유사 배열 객체다.
    	for (let i=0; i<arguments.length; i++) {
    		res += arguments[i];
    	}
    
    	return res;
    }
    
    console.log(sum()); // 0
    console.log(sum(1,2)); // 3
    console.log(sum(1,2,3)); // 6
    

    유사 배열 객체는 배열이 아니므로 배열 메서드를 사용할 경우 에러가 발생한다.

    배열 메서드를 사용하기 위해서는 Function.prototype.call 이나 Function.prototype.apply 를 사용해 간접 호출해야 한다.

    function sum() {
    	// arguments 객체를 배열로 변환
    	const array = Array.prototype.slice.call(arguments);
    	return array.reduce(function (pre, cur) {
    		return pre + cur;
    	}, 0);
    }
    
    console.log(sum(1,2)); // 3
    

    ES6에서는 Rest 파라미터가 도입됐다.

    // ES6 Rest parameter
    function sum(...args) {
    	return args.reduce((pre, cur) => pre + cur, 0);
    }
    
    console.log(sum(1,2)); // 3
    
  2. caller 프로퍼티

  3. length 프로퍼티

    함수 객체의 length 프로퍼티는 함수를 정의할 때 선언한 매개변수의 개수를 가리킨다.

    function foo() {}
    console.log(foo.length); // 0
    
    function bar(x) { return x; }
    console.log(bar.length); // 1
    
  4. name 프로퍼티

  5. __proto__ 접근자 프로퍼티

    모든 객체는 [[Prototype]] 이라는 내부 슬롯을 갖는다.

  6. prototype 프로퍼티 생성자 함수로 호출할 수 있는 함수 객체, 즉 constructor만이 소유하는 프로퍼티다. 일반 객체와 생성자 함수로 호출할 수 없는 non-constructor에는 prototype 프로퍼티가 없다.

function forEachObject(obj, fn) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key];
      fn(value, key);
    }
  }
}

const fns = [
	() => console.log(1), 
	() => console.log(2), 
	() => console.log(3)
];

const obj = {
  a: fns[0],
  b: fns[1],
  c: fns[2]
};

forEachObject(obj, (fn) => fn());