모던 JS DeepDive(18장)

Minji Lee·2025년 2월 19일
0

18.1 일급 객체

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

자바스크립트의 함수는 일급 객체다!

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

18.2 함수 객체의 프로퍼티

함수는 객체이므로 프로퍼티를 가질 수 있다!console.dir 메서드 사용하여 함수 객체 내부 확인

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 함수의 프로퍼티가 아님!
// __proto__는 Object.prototype 객체의 접근자 프로퍼티임!
// square 함수는 Object.prototype 객체로부터 __proto__ 접근자 프로퍼티 상속받음
console.log(Object.getOwnPropertyDescriptor(square, '__proto__')); // undefined
  • arguments, caller, length, name, prototype 프로퍼티는 모두 함수 객체의 데이터 프로퍼티
  • __proto__는 접근자 프로퍼티이며, 함수 객체 고유의 프로퍼티가 아니라 Object.prototype 객체의 프로퍼티를 상속받은 것! ⇒ Object.prototype 객체의 프로퍼티는 모든 객체가 상속받아 사용할 수 있다.

18.2.1 arguments 프로퍼티

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

arguments 객체는 함수 호출 시 전달된 인수들의 정보를 담고 있는 순회가능한 유사 배열 객체

function multiply(x, y) {
  console.log(arguments);
  return x + y;
}

console.log(multiply()); // NaN [Arguments] {}
console.log(multiply(1)); // NaN [Arguments] { '0': 1 }
console.log(multiply(1, 2)); // 3 [Arguments] { '0': 1, '1': 2 }
console.log(multiply(1, 2, 3)); // 3 [Arguments] { '0': 1, '1': 2, '2': 3 }
  • 함수 호출되면 함수 몸체 내에서 암묵적으로 매개변수 선언되고 undefined로 초기화된 이후 인수가 할당됨
  • 선언된 매개변수의 개수보다 인수 적게 전달했을 경우 인수가 전달되지 않은 매개변수는 undefined로 초기화된 상태 유지
  • 인수를 더 많이 전달한 경우 초과된 인수는 무시됨! 초과된 인수는 버려지는 것이 아닌 암묵적으로 모든 인수는 arguments 객체의 프로퍼티로 보관됨

[arguments 객체의 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;
    
      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
    • arguments 객체는 실제 배열이 아닌 유사 배열 객체임!

      유사 배열 객체: length 프로퍼티를 가진 객체로 for 문으로 순회할 수 있는 객체

      • ES6에서 도입된 이터레이터 프로토콜 준수하면 순회 가능한 자료구조인 이터러블이 됨! ES6부터 arguments 객체는 유사배열 객체이면서 동시에 이터러블이다.
    • 배열 메서드 사용할 경우 에러 발생함 ⇒ 배열 메서드 사용하려면 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()); // 0
      console.log(sum(1, 2)); // 3
    • ES6부터는 Rest 파라미터 도입하여 번거로움 해결
      function sum(...args) {
        return args.reduce((pre, cur) => pre + cur, 0);
      }
      
      console.log(sum()); // 0
      console.log(sum(1, 2)); // 3

18.2.2 caller 프로퍼티

caller 프로퍼티는 ECMAScript 사양에 포함되지 않은 비표준 프로퍼티로, 함수 자신을 호출한 함수 가리킴

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

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

console.log(foo(bar)); // Caller: function foo(func) { return 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
  • arguments 객체의 length 프로퍼티는 인자의 개수이고, 함수 객체의 length 프로퍼티는 매개변수 개수임!

18.2.4 name 프로퍼티

함수의 이름을 나타냄

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

// 익명 함수 표현식
// 함수 객체 가리키는 식별자를 값으로 갖는다.
const anonymousFunc = function () {};
console.log(anonymousFunc.name); // anonymousFunc

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

18.2.5 proto 접근자 프로퍼티

모든 객체는 [[Prototype]]이라는 내부 슬롯을 갖는다. [[Prototype]] 내부 슬롯은 객체지향 프로그래밍의 상속을 구현하는 프로토타입 객체를 가리킴

__proto__ 프로퍼티: [[Prototype]] 내부 슬롯이 가리키는 프로토타입 객체에 접근하기 위해 사용하는 접근자 프로퍼티

  • 내부 슬롯에 직접 접근 X, 간접적인 접근 방법을 제공하는 경우에만 접근 가능!
const obj = { a: 1 };

console.log(obj.__proto__ === Object.prototype); // true

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

hasOwnProperty 메서드: 인수로 전달받은 프로퍼티 키가 객체 고유의 프로퍼티 키인 경우에만 true 반환, 상속받은 프로토타입의 프로퍼티 키false 반환

18.2.6 prototype 프로퍼티

prototype 프로퍼티는 함수가 객체를 생성하는 생성자 함수로 호출될 때 생성자 함수가 생성할 인스턴스 프로토타입 객체 가리킴

생성자 함수로 호출할 수 있는 함수 객체, 즉 constructor만이 소유하는 프로퍼티임!

일반 객체와 생성자 함수로 호출할 수 없는 non-constructor에는 prototype 프로퍼티 없음

(function () {}).hasOwnProperty('prototype'); // true

({}).hasOwnProperty('prototype'); // false

0개의 댓글