생성자 : 객체를 만드는 역할을 하는 함수. 객체의 구조를 재활용 할때 사용하는 것이다. 자바스크립트에서 함수는 객체를 만드는 창조자이다. 그리고 함수를 호출할 때 new를 붙이면 새로운 객체를 만든 후에 이를 리턴한다. 생성자 함수는 일반 함수와 구분하기 위해서 첫글자를 대문자로 표시한다.


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

 

//
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());

'Programming > Javascript' 카테고리의 다른 글

상속, prototype  (0) 2018.01.03
전역객체와 this  (0) 2018.01.03
함수의 호출  (0) 2018.01.03
arguments, 매개변수의 수  (0) 2018.01.03
내부함수와 클로저  (0) 2018.01.03
블로그 이미지

꼴통보안인

,