ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Javascript]함수와 일급 객체
    카테고리 없음 2022. 3. 1. 21:18

    #모던자바스크립트_딥다이브 스터디를 진행하면서 정리한 내용입니다.

    일급 객체

    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
    console.log(increaser()); // 2
    
    // 3. 함수는 매개변수에게 함수를 전달할 수 있다.
    const decreaser = makeCounter(auxs.decrease);
    console.log(decreaser()); // -1
    console.log(decreaser()); // -2

    함수가 일급 객체라는 것은 함수를 객체와 동일하게 사용할 수 있다는 의미이다. 객체는 값이므로 함수는 값과 동일하게 취급한다. 

    함수는 일반 객체와 같이 함수의 매개변수에 전달할 수 있으며, 함수의 반환값으로 사용할 수도 있다는 것이다. 

     

    함수 객체의 프로퍼티

    함수는 객체다. 따라서 함수도 프로퍼티를 가질 수 있다. argument, caller, length, name,prototype 모두 함수 객체의 데이터 프로퍼티다.

    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}

     

    1) arguments

    함수 객체의 argumeents는 객체이다. 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

    다만 무시된다고 해도 그냥 버려지는 것은 아니다. 모든 인수는 암묵적으로 arguments 객체의 프로퍼티로 보관된다.

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

     

    *arguments 객체의 Symbol.iterator 프로퍼티

    arguments 객체의 Symbol 프로퍼티는 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

    다만 argument는 유사배열객체이므로 진짜 배열은 아니다. 따라서 일반적인 배열 메서드를 사용할 때는 에러가 발생하므로, Array.prototype.slice를 이용하여 배열 메서드를 사용할 수 있다.

    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

     

    2) caller 프로퍼티

    함수 객체의 calller 프로퍼티는 함수 자신을 호출한 함수를 가리킨다.

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

     

    3) length 프로퍼티

    함수 객체의 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 프로퍼티는 인자의 개수를 가리키고, 함수 객체의 length 프로퍼티는 매개변수의 개수를 가리킨다.

     

    4) name 프로퍼티

    name 프로퍼티는 ES5와 ES6에서 동작을 달리하므로 주의해야 한다. 익명 함수 표현식의 경우 ES5에서 name 프로퍼티는 빈 문자열을 값으로 갖는다. 하지만 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

     

    5) __proto__ 접근자 프로퍼티

    __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

    * hasOwnProperty 메서드

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

     

    6) prototype 프로퍼티

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

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

    댓글

Designed by Tistory.