생성자와 new
자바스크립트는 prototype-based programming이라고 한다.
객체란 서로 연관된 변수와 함수(메소드)를 그룹핑한 그릇이라고 할 수 있다. 객체 내의 변수를 property(속성), 함수를 method(메소드)라고 부른다.
var person = {//객체 선언과 객체의 속성, 메소드를 따로 정의할 수도 있다.
person.name = 'egoing';
person.introduce = function() {
return 'My name is '+this.name;//여기서 this는 함수가 속해있는 객체를 가리킨다!
}
}
document.write(person.introduce());
응집성과 가독성을 높이기 위해 위의 코드처럼 작성하는 것이 맞지만, 아래의 코드처럼 객체 선언과 객체의 속성, 메소드를 따로 정의할 수도 있다.
var person = {}
person.name = 'egoing';
person.introduce = function() {
return 'My name is '+this.name;//여기서 this는 함수가 속해있는 객체를 가리킨다!
}
document.write(person.introduce());
실행 결과

아래의 코드에서는 2개의 객체를 생성하였다. 이 때, 2개의 객체가 모두 같은 메소드를 사용한다면 이것은 중복된다. 이것은 코드의 양이 길어지고, 가독성을 떨어트리고, 유지보수가 어려워진다. 이러한 문제를 생성자 new로 해결할 수 있다.
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를 붙이면 그 리턴값은 객체가 된다.
function person() {}
var p0 = person();
var p = new person();//실행 결과 : Person{}
생성자 내에서 객체의 속성을 정의하면 코드의 재사용성이 높아진다. 이러한 작업을 초기화라고 한다. 즉, 초기화를 통해 한번만 정의하면 계속 사용할 수 있다.
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 />");
Last updated
Was this helpful?