궁금한게 많은 열아홉

일급 객체

우리는 다음과 같은 조건을 만족하는 객체를 일급객체라고 한다.

  • 무명의 리터럴로 생성할 수 있다. 즉, 런타입에 생성이 가능하다.
  • 변수나 자료구조(객체, 배열) 등에 저장할 수 있다.
  • 함수의 매개변수에 전달 할 수 있다.
  • 함수의 반환값으로 사용할 수 있다.
// 1. 함수는 무명의 리터럴로 샐성할 수 있다.
    // 2. 함수는 변수에 저장 할 수 있다.
    // 런타입(할당 단계)에 함수 리터럴이 평가되어 함수 객체가 생성되고 변수에 할당된다.
    const inc = function (num) {
      return ++num;
    };
    const dec = function (num) {
      return --num;
    };

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

    // 3. 함수의 매개변수에 전달할 수 있다.
    // 4. 함수의 반환값으로 사용할 수 있다.
    function makeCounter(aux) {
      let num = 0;

      return function () {
        num = aux(num);
        return num;
      };
    }

    // 3. 함수는 매개변수에게 함수를 전달 할 수 있음
    const increaser = makeCounter(auxs.inc);
    console.log(increaser()); // 1
    console.log(increaser()); // 2

    // 3. 함수는 매개변수에게 함수를 전달 할 수 있음
    const decreaser = makeCounter(auxs.dec);
    console.log(decreaser()); // -1
    console.log(decreaser()); // -2
  • 함수 = 일급 객체
  • 객체와 함수를 동일하게 사용할 수 있음.
  • 하지만, 둘은 호출 여부에 대한 차이가 있다는 걸 명심해야 함.

함수 객체의 프로퍼티

  • 함수 = 객체 이므로 프로퍼티를 가질 수 있음
function square(num) {
      return num * num;
    }
    console.dir(square);

square함수의 모든 프로퍼티의 어트리뷰트를 Object.getOwnPropertyDescriptors 메서드로 확인 가능

// 18-3
    function square(num) {
      return num * num;
    }
    console.log(Object.getOwnPropertyDescriptors(square));
    // {length: Object, name: Object, arguments: Object, caller: Object, prototype: Object}
    // length: Object
    // value: 1
    // writable: false
    // enumerable: false
    // configurable: true
    // name: Object
    // value: "square"
    // writable: false
    // enumerable: false
    // configurable: true
    // arguments: Object
    // value: null
    // writable: false
    // enumerable: false
    // configurable: false
    // caller: Object
    // value: null
    // writable: false
    // enumerable: false
    // configurable: false
    // prototype: Object
    // value: Object
    // writable: true
    // enumerable: false
    // configurable: false

    // __proto__는 sqaure함수의 프로퍼티가 아님
    console.log(Object.getOwnPropertyDescriptors(square, "__proto__"));

    // __proto__는 Object,prototype 객체의 접근자 프로퍼티
    // square함수는 Object,prototype 객체로 부터 __proto__접근자 프로퍼티를 상속받은
    console.log(
      Object.getOwnPropertyDescriptors(Object.prototype, "__proto__")
    );

arguments프로퍼티

  • 함수 객체의 arguments 프로퍼티 값은 arguments 객체다.
  • 호출 시 전당된 인수들의 정보를 담고있는 순회 가능한 유사 배열 객체이다
  • 함수 내부에서 지역 변수로 사용 가능
  • 함수 외부에서 참조 불가     
// 18-4
    function mul(x, y) {
      console.log(arguments);
      return x * y;
    }
    console.log(mul()); // NaN
    console.log(mul(1)); // NaN
    console.log(mul(1, 2)); // 2
    console.log(mul(1, 2, 3)); // 2

arguments 객체의 Symbol(Symbol.iterator) 프로퍼티

  • 객체를 순회 가능한 자료구조인 이터러블로 만들기 위한 프로퍼티
// 18-5
    function mul(x, y) {
      // 이터레이터
      const iter = arguments[Symbol.iterator]();

      // 이터레이터의 next 메서드 호출해 객체 arguments를 순화
      console.log(iter.next()); // {value: 1, done: false}
      console.log(iter.next()); // {value: 2, done: false}
      console.log(iter.next()); // {value: 3, done: false}
      console.log(iter.next()); // {value: undefined, done: true}
      return x * y;
    }

    mul(1, 2, 3);

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

// 18-6
    function sum(x, y) {
      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

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

그럼 어떻게 하죠 ..?

  • Function.prototype.call, Function.prototype.apply를 사용해 간접 호출 해야지 ..
// 18-7
    function sum(x, y) {
      // arguments 객체를 배열로 변환.
      const arr = Array.prototype.slice.call(arguments);
      return arr.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 파라미터를 도입 !(훗 ㅋ)
// 18-8
    // 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

caller 프로퍼티

  • ECMAScript 사양에 포함되지 않은 비표준 프로퍼티
// 18-9
    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

length 프로퍼티

  • 함수 객체의 length프로퍼티는 함수를 정의할 때 선언한 매개변수의 개수를 가리킴
// 18-10
    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

name 프로퍼티

  • 함수 객체의 name프로퍼티는 함수 이름을 나타냄
// 18-11

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

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

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

__proto__ 접근자 프로퍼티

  • 모든 객체는 [[Prototype]]이라는 내부슬롯을 가짐
  • __property__는 [[Prototype]] 내부 슬롯이 가리키는 프로토 타입 객체에 접근하기위해 사용하는 접근자 프로퍼티이다.
// 18-12

    const obj = { a: 1 };

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

    // 객체 리터럴 방식으로 생성한 객체는 프로토타입 객체인 Object.prototype을 상속 받음
    // hasOwnProperty 메서드는 Object.prototype의 메서드다.
    console.log(obj.hasOwnProperty("a"));
    console.log(obj.hasOwnProperty("__proto__"));
  • hasOwnProperty 메서드 : 인수로 전달 받은 프로퍼티키가 객체 고유의 프로퍼티인 경우에만 true를 반환하고 상속받은 프로토타입의 프로퍼티 키인 경우 false를 반환한다.

prototype 프로퍼티

  • 생성자 함수로 호출 할 수 있는 함수 객체, 즉 construct만이 소유하는 프로퍼티
// 18-13

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

    // 일반 객체는 prototype 프로퍼티를 소유하지 않는다.
    ({}.hasOwnProperty("prototype")); // false

 

profile

궁금한게 많은 열아홉

@jjin502

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!