# 18 함수와 일급 객체

## 18.1 일급 객체

아래의 조건을 만족하면 일급 객체이다.

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

JS의 함수는 위의 조건을 모두 만족하므로 일급 객체다.

함수가 일급 객체이기에 함수를 객체와 동일하게 사용할 수 있으며, 객체는 값이므로 함수는 값과 동일하게 사용할 수 있다. 따라서 함수는 값을 사용할 수 있는 곳에 어디서든 리터럴로 정의할 수 있으며 런타임에 함수 객체로 평가된다.&#x20;

함수가 일급 객체이기에 가지는 가장 큰 특징은 함수의 매개변수에 전달할 수 있고, 함수의 반환값으로 사용할 수 있다는 점인데, 이는 [함수형 프로그래밍](https://wlgus3.gitbook.io/jhs-modern-js-deep-dive-note/12#12.7.5)을 가능케 하는 JS의 장점 중 하나다.

단, 일반객체는 호출할 수 없지만 함수객체는 호출할 수 있으며, 일반 객체에는 없는 함수 고유의 프로퍼티를 소유한다.

## 18.2 함수 객체의 프로퍼티

함수는 객체다. 따라서 함수도 프로퍼티를 가질 수 있다.

&#x20;console.dir 메서드로 함수 객체 내부를 들여다볼 수 있다.&#x20;

```javascript
function square(number) {
  return number * number;
}

console.dir(square);
```

```javascript
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}
```

arguments, caller, name, prototype 프로퍼티는 모두 함수 객체의 데이터 프로퍼티이며, 일반 객체에는 없는 함수 객체 고유의 프로퍼티다. 하지만 \_\_proto\_\_는 접근자 프로퍼티이며, Object.prototype 객체의 프로퍼티를 상속받은 것을 알 수 있다.

Object.prototype 객체의 모든 프로퍼티는 모든 객체가 상속받아 사용할 수 있으며, Object.prototype의 \_\_proto\_\_ 접근자 프로퍼티는 모든 객체가 사용 가능하다.

### 18.2.1 arguments 프로퍼티

arguments 객체는 함수 호출 시 **전달된 인수(argument)들의 정보**를 담고 있는 **순회가능한(iterable) 유사 배열 객체(array-like object)**&#xC774;며 함수 내부에서 지역변수처럼 사용된다. 즉, 함수 외부에서는 사용할 수 없다.

{% hint style="info" %}
**매개변수(parameter)**&#xB780; 함수의 정의에서 전달받은 **인수를 함수 내부로 전달하기 위해 사용하는 변수**를 의미.

**인수(argument)**&#xB780; 함수가 호출될 때 함수로 **전달해주는 값**.
{% endhint %}

```javascript
function multiply(x, y) {
  console.log(arguments);
  return x * y;
}

multiply();        
multiply(1);       
multiply(1, 2);    
multiply(1, 2, 3); 
```

<figure><img src="https://45367248-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FdJ0EyH216Xh9SDawFrKd%2Fuploads%2Fx19IFUbItmnDBYwJ4fy6%2Fimage.png?alt=media&#x26;token=917985dc-8afd-41fa-a6cd-1ee6eab4b3c0" alt=""><figcaption><p>Arguments내부의 인수정보</p></figcaption></figure>

자바스크립트는 함수 호출 시 함수 정의에 따라 **인수를 전달하지 않아도 에러가 발생하지 않는다.**

* 매개변수의 갯수보다 인수를 적게 전달했을 때 전달되지 않은 매개변수는 `undefined`으로 초기화된다.
* 매개변수의 갯수보다 인수를 더 많이 전달한 경우, 초과된 인수는 무시된다.

이러한 자바스크립트의 특성때문에 **런타임 시**에 호출된 함수의 **인자 갯수를 확인**하고 **이에 따라 동작을 달리 정의할 필요가 있을 수 있다.** 이때 유용하게 사용되는 것이 arguments 객체이다.

arguments 객체는 **매개변수 갯수가 확정되지 않은 가변 인자 함수를 구현할 때 유용**하게 사용된다.

```javascript
function sum() {
  var res = 0;

  for (var 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 객체는 배열의 형태를 가졌지만 실제 배열은 아닌 \[유사배열객체] array-like-object 이다.

유사배열객체는 length 프로퍼티를 가지고있고 for문으로 순회할 수 있는 객체이며, 배열 메서드를 사용하려면 Function.prototype.call , Function.prototype.apply를 사용해야 한다.

```javascript
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 파라미터]**&#xC758; 도입으로 모던 JS에서는 elements 객체의 중요성이 떨어졌지만 ES6 이전 버전을 사용할 경우를 대비해 알아놓는 것이 좋다.

&#x20;**-** [**Rest 파라미터**](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters) : 함수가 정해지지 않은 수의 매개변수를 배열로 받을 수 있도록 해줌

```javascript
function sum(...theArgs) { // ...theArgs가 Rest 파라미터 
  let total = 0;
  for (const arg of theArgs) {
    total += arg;
  }
  return total;
}

console.log(sum(1, 2, 3));
// Expected output: 6

console.log(sum(1, 2, 3, 4));
// Expected output: 10
```

### 18.2.2 caller 프로퍼티&#x20;

ECMAscript 사양에 포함되지 않았으며 예정도 없기에 사용하지 말고 참고만 하자.

caller 프로퍼티는 **자신을 호출한 함수**를 의미한다.

```javascript
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 프로퍼티&#x20;

length 프로퍼티는 함수를 정의할 때 선언한 프로퍼티의 개수를 가리킨다.&#x20;

\*arguments 객체의 length는 인자의 수 != 함수객체의 length= 매개변수의 수

```javascript
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
```

### 18.2.4 name 프로퍼티&#x20;

함수 객체의 name 프로퍼티는 함수의 이름을 나타낸다.

단 ES5, ES6의 동작방식이 다르다. 익명함수일 때 ES5에서는 빈 문자열을 반환하고, ES6에서는 **함수 객체를 가리키는 식별자**를 반환한다.&#x20;

{% hint style="danger" %}
[12.4.1 함수 선언문](https://wlgus3.gitbook.io/jhs-modern-js-deep-dive-note/12#12.4.1) 에서 살펴본 바와 같이 <mark style="color:purple;">**함수 이름**</mark>과 <mark style="color:purple;">**함수 객체를 가리키는 식별자**</mark>는 **의미가 다르다**는 것을 기억하자!! **함수를 호출할 때**에는 함수 이름이 아닌 **함수를 가리키는 식별자로 호출**한다.&#x20;
{% endhint %}

### 18.2.5 \_\_proto\_\_ 접근자 프로퍼티&#x20;

&#x20;**모든 객체는 \[\[Prototype]]이라는 내부 슬롯이 있다.** **\[\[Prototype]] 내부 슬롯**은 **프로토타입 객체**를 가리킨다. 프로토타입 객체란 **프로토타입 기반 객체 지향 프로그래밍의 근간을 이루는 객체**로서 **객체간의 상속(Inheritance)을 구현하기 위해 사용**된다. 즉, 프로토타입 객체는 **다른 객체에 공유 프로퍼티를 제공하는 객체**를 말한다.

\_\_proto\_\_ 프로퍼티는 \[\[Prototype]] 내부 슬롯이 가리키는 **프로토타입 객체에 접근하기 위해 사용하는 '접근자 프로퍼티'**&#xC774;다. 내부 슬롯에는 **직접 접근할 수 없고** **간접적인 접근** 방법을 제공하는 경우에 한하여 접근할 수 있다. \[\[Prototype]] 내부 슬롯에도 직접 접근할 수 없으며 \_\_proto\_\_ 접근자 프로퍼티를 통해 간접적으로 프로토타입 객체에 접근할 수 있다.

```javascript
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
```

{% hint style="info" %}
**hasOwnProperty** 메서드 : 인수로 전달받은 프로퍼티 키가 객체 고유의 프로퍼티인 경우에만 true를 반환한다. 상속받은 프로퍼티 키인 경우는 false
{% endhint %}

### 18.2.6 prototype 프로퍼티

prototype 프로퍼티는 생성자 함수로 호출할 수 있는 객체, 즉 constructor만이 소유하는 프로퍼티이다.&#x20;

prototype 프로퍼티는 함수가 객체를 생성하는 생성자 함수로 사용될 때, 생성자 함수가 생성한 인스턴스의 프로토타입 객체를 가리킨다.

\ <a href="#id-7" id="id-7"></a>
--------------------------------


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wlgus3.gitbook.io/jhs-modern-js-deep-dive-note/18.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
