[모던 자바스크립트 Deep Dive] 18장. 함수와 일급 객체

윤상준·2022년 12월 18일
0
post-thumbnail

18.1 일급 객체

일급 객체의 조건

  • 무명의 리터럴로 생성 가능. 즉, 런타임에서 생성이 가능.
  • 변수나 자료 구조에 저장이 가능.
  • 함수의 매개 변수에 전달이 가능.
  • 함수의 반환값으로 사용이 가능.

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

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

일급 객체라는 의미는 함수를 객체와 동일하게 사용이 가능하다는 의미이다.
함수의 매개변수, 반환값으로 사용할 수 있다는 특징으로 인해 자바스크립트의 함수형 프로그래밍이 가능해진다.
하지만 함수는 일반 객체와는 차이가 있다.
일반 객체는 호출할 수 없지만 함수는 호출이 가능하다. 또한 함수 객체는 일반 객체에는 없는 함수 고유의 프로퍼티를 소유한다.

18.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}

__proto__는 함수 객체의 고유 프로퍼티가 아닌, Object.prototype 객체의 프로퍼티를 상속 받는다.

18.2.1 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
  • caller 프로퍼티 : 호출되어 arguments 객체를 생성한 함수. (함수 자기 자신)
  • length 프로퍼티 : 인수의 개수.
  • Symbol (Symbol.iterator) 프로퍼티 : arguments 객체를 순회 가능한 자료구조인 이터러블로 만들기 위한 프로퍼티.
function multiply(x, y) {
  // 이터레이터
  const iterator = arguments[Symbol.iterator]();

  // 이터레이터의 next 메서드를 호출하여 이터러블 객체 arguments를 순회
  console.log(iterator.next()); // {value: 1, done: false}
  console.log(iterator.next()); // {value: 2, done: false}
  console.log(iterator.next()); // {value: 3, done: false}
  console.log(iterator.next()); // {value: undefined, done: true}

  return x * y;
}

multiply(1, 2, 3);

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

function sum() {
  let res = 0;

  // arguments 객체는 length 프로퍼티가 있는 유사 배열 객체이므로 for 문으로 순회할 수 있다.
  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

ES5 까지 arguments 객체는 유사 배열 객체로 구분되었기 때문에 배열이 아니었다.
따라서 배열 메서드를 사용할 경우 에러가 발생했다.
ES6부터 이터러블이 도입되어 arguments 객체는 유사 배열 객체이면서 동시에 이터러블이 되었다.

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
console.log(sum(1, 2, 3, 4, 5)); // 15
// ES6 Rest parameter
function sum(...args) {
  return args.reduce((pre, cur) => pre + cur, 0);
}

console.log(sum(1, 2));          // 3
console.log(sum(1, 2, 3, 4, 5)); // 15

18.2.2 caller 프로퍼티

ECMAScript 사양에 포함되지 않는 비표준 프로퍼티.

function foo(func) {
  return func();
}

function bar() {
  return 'caller : ' + bar.caller;
}

// 브라우저에서의 실행한 결과
console.log(foo(bar)); // caller : function foo(func) {...}
console.log(bar());    // caller : null

18.2.3 length 프로퍼티

함수를 정의할 때 선언한 매개변수의 개수.

function foo() {}
console.log(foo.length); // 0

function bar(x) {
  return x;
}
console.log(bar.length); // 1

function baz(x, y) {
  return x * y;
}
console.log(baz.length); // 2

arguments 객체의 length 프로퍼티 : 인자 (argument)의 개수.
함수 객체의 length 프로퍼티 : 매개변수 (parameter)의 개수.

18.2.4 name 프로퍼티

함수 이름을 나타내며 ES6부터 정식 표준이 되었다.
ES5와 ES6에서 동작을 달리한다는 점에 주의가 필요하다.
ES5에서는 빈 문자열을 값으로 갖는 반면, ES6에서는 함수 객체를 가리키는 식별자를 값으로 갖는다.

// 기명 함수 표현식
var namedFunc = function foo() {};
console.log(namedFunc.name); // foo

// 익명 함수 표현식
var anonymousFunc = function() {};
// ES5: name 프로퍼티는 빈 문자열을 값으로 갖는다.
// ES6: name 프로퍼티는 함수 객체를 가리키는 변수 이름을 값으로 갖는다.
console.log(anonymousFunc.name); // anonymousFunc

// 함수 선언문(Function declaration)
function bar() {}
console.log(bar.name); // bar

18.2.5 __proto__ 접근자 프로퍼티

[[Prototype]] 내부 슬롯이 가리키는 프로토타입 객체에 접근할 수 있는 접근자 프로퍼티.

const obj = { a: 1 };

// 객체 리터럴 방식으로 생성한 객체의 프로토타입 객체는 Object.prototype이다.
console.log(obj.__proto__ === Object.prototype); // true

// 객체 리터럴 방식으로 생성한 객체는 프로토타입 객체인 Object.prototype의 프로퍼티를 상속받는다.
// hasOwnProperty 메서드는 Object.prototype의 메서드다.
console.log(obj.hasOwnProperty('a'));         // true
console.log(obj.hasOwnProperty('__proto__')); // false

18.2.6 prototype 프로퍼티

생성자 함수로 호출할 수 있는 constructor 만 소유할 수 있는 프로퍼티.
반대로 non-constructor 에는 존재하지 않는다.

// 함수 객체는 prototype 프로퍼티를 소유한다.
(function () {}).hasOwnProperty('prototype'); // -> true

// 일반 객체는 prototype 프로퍼티를 소유하지 않는다.
({}).hasOwnProperty('prototype'); // -> false
profile
하고싶은건 많은데 시간이 없다!

0개의 댓글