생성자와 new

객체

객체란 서로 연관된 변수와 함수를 그룹핑한 그릇이라고 할 수 있다. 객체 내의 변수를 프로퍼티(property) 함수를 메소드(method)라고 부른다.

var person = {} // 비어있는 객체 
person.name = 'egoing'; // 프로퍼티
person.introduce = function(){//메소드
    return 'My name is '+this.name; 
}
document.write(person.introduce()); // My name is egoing 

// 좀더 나은 방법 
var person = {
    'name' : 'egoing', // 프로퍼티
    'introduce' : function(){ //메소드
        return 'My name is '+this.name;
    }
}
document.write(person.introduce()); // My name is egoing 

생성자

생성자(constructor)는 객체를 만드는 역할을 하는 함수다. 자바스크립트에서 함수는 재사용 가능한 로직의 묶음이 아니라 객체를 만드는 창조자라고 할 수 있다.

function Person(){}
var p = new Person(); // new 아주 중요함 -> new 가 붙어있는 함수를 객체의 생성자라고 한다. 
// 함수에 new를 붙이면 그것은 객체가 된다. 
p.name = 'egoing';
p.introduce = function(){
    return 'My name is '+this.name; 
}
document.write(p.introduce()); // My name is egoing
function Person(name){ // 생성자 생성 
    this.name = name; // eging
    this.introduce = function(){
        return 'My name is '+this.name; 
    }   
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />"); //  My name is egoing
 
var p2 = new Person('leezche');
document.write(p2.introduce());  //  My name is leezche

생성자 내에서 이 객체의 프로퍼티를 정의하고 있다. 이러한 작업을 초기화라고 한다. 이를 통해서 코드의 재사용성이 대폭 높아졌다.

코드를 통해서 알 수 있듯이 생성자 함수일반함수와 구분하기 위해서 첫글자를 대문자로 표시한다.

Last updated