생성자와 new

1. 객체

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

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

2. 생성자와 new

2-1. 생성자(Contructor)

객체를 만드는 역할을 하는 함수

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

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

2-2. new

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

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를 정의하는 것

//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());
//초기화 결과
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());

Last updated