# 생성자와 new

## 1. 객체

> **서로 연관된 변수와 함수를 그룹핑(Grouping)한 그릇**이라고 할 수 있음\
> 객체 내의 **변수 프로퍼티(property)**, **함수를 메소드(method)**&#xB77C;고 부름

{% tabs %}
{% tab title="예시1" %}

```javascript
var person = {}
person.name = 'egoing';
person.introduce = function(){
    return 'My name is '+this.name;
}
document.write(person.introduce());
//위 코드는 객체를 만드는 과정에 있어서 분산되어 있어
//중간에 다른 내용이 끼기 쉬움
```

{% endtab %}

{% tab title="예시2" %}

```javascript
var person = {
    'name' : 'egoing',
    'introduce' : function(){
        return 'My name is '+this.name;
    } //{}를 사용해서 grouping하여 가독성도 좋고, 내용이 분산되지 않음
}
document.write(person.introduce());
```

{% endtab %}
{% endtabs %}

## 2. 생성자와 new

### 2-1. 생성자(Contructor)

> **객체를 만드는 역할**을 하는 함수
>
> 생성자 함수는 일반함수와 구분하기 위해서 **첫글자를 대문자로** 표시함\
> 객체의 정의가 반복되지 않도록 구조를 재사용할 수 있게 해 줌

```javascript
function Func_name(){}
var name = new Func_name(){}; 
```

### 2-2. new

> 함수를 호출할 때 **new**를 붙이면 **새로운 객체를 만든 후 이를 리턴함**

```javascript
function Person(){}
var p = new Person();
p.name = 'egoing';
p.introduce = function(){
    return 'My name is '+this.name; 
}
document.write(p.introduce());
```

### 2-3. 초기화작업

> 생성자 내에서 **객체의 Property를 정의**하는 것

```javascript
//1차 초기화
function Person(){}
var p1 = new Person();
p1.name = 'egoing';
p1.introduce = function(){
    return 'My name is '+this.name; 
}
document.write(p1.introduce()+"<br />");
 
var p2 = new Person();
p2.name = 'leezche';
p2.introduce = function(){
    return 'My name is '+this.name; 
}
document.write(p2.introduce());
```

```javascript
//초기화 결과
function Person(name){
    this.name = name;
    this.introduce = function(){
        return 'My name is '+this.name; 
    }   
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
 
var p2 = new Person('leezche');
document.write(p2.introduce());
```


---

# 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://westsilver.gitbook.io/study-script/javascript/jacascript-start/undefined-2/new.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.
