> For the complete documentation index, see [llms.txt](https://heunnajo.gitbook.io/javascript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://heunnajo.gitbook.io/javascript/new.md).

# 생성자와 new

자바스크립트는 prototype-based programming이라고 한다.

객체란 서로 연관된 변수와 함수(메소드)를 그룹핑한 그릇이라고 할 수 있다. 객체 내의 변수를 property(속성), 함수를 method(메소드)라고 부른다.&#x20;

```javascript
var person = {//객체 선언과 객체의 속성, 메소드를 따로 정의할 수도 있다.
    person.name = 'egoing';
    person.introduce = function() {
        return 'My name is '+this.name;//여기서 this는 함수가 속해있는 객체를 가리킨다!
    }
}
document.write(person.introduce());
```

응집성과 가독성을 높이기 위해 위의 코드처럼 작성하는 것이 맞지만, 아래의 코드처럼 객체 선언과 객체의 속성, 메소드를 따로 정의할 수도 있다.

```javascript
var person = {}
person.name = 'egoing';
person.introduce = function() {
    return 'My name is '+this.name;//여기서 this는 함수가 속해있는 객체를 가리킨다!
}
document.write(person.introduce());
```

**실행 결과**

![](https://2105797137-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MECuHZ1KfvGBZfxLj0-%2F-MEhHO5OJhFsdJLc7np8%2F-MEhHWgfp1l6L4CKli4X%2FScreen%20Shot%202020-08-14%20at%2011.04.56%20PM.png?alt=media\&token=f6fe9e79-ebad-4e90-a978-9a5374e5961e)

아래의 코드에서는 2개의 객체를 생성하였다. 이 때, 2개의 객체가 모두 같은 메소드를 사용한다면 이것은 중복된다. 이것은 코드의 양이 길어지고, 가독성을 떨어트리고, 유지보수가 어려워진다. 이러한 문제를 생성자 new로 해결할 수 있다.

```javascript
var person1 = {
    person.name = 'egoing';
    person.introduce = function() {
        return 'My name is '+this.name;//여기서 this는 함수가 속해있는 객체를 가리킨다!
    }
}
var person2 = {
    person.name = 'leezche';
    person.introduce = function() {
        return 'My name is '+this.name;//여기서 this는 함수가 속해있는 객체를 가리킨다!
    }
}
```

정의되지 않은 함수를 변수에 할당하면 그 변수 값 역시 'undefined'이다.

**var p = new person();**

앞에 new가 붙어있으면 person()은 함수가 아니라 **생성자**이다. 생성자는 비어있는 객체를 만들고 이를 반환한다.**함수는 단순히 어떤 기능을 수행하는 것이 아니라 new를 만나면 객체를 생성하기도 한다**. 즉, 함수에 new를 붙이면 그 리턴값은 객체가 된다.

```javascript
function person() {}
var p0 = person();
var p = new person();//실행 결과 : Person{}
```

생성자 내에서 객체의 속성을 정의하면 코드의 재사용성이 높아진다. 이러한 작업을 초기화라고 한다. 즉, 초기화를 통해 한번만 정의하면 계속 사용할 수 있다.&#x20;

```javascript
function person(name){
    this.name = name;//person 함수가 속한 객체의 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()+"<br />");
```
