JavaScript/생활코딩

자바스크립트 기본 - 생성자와 new

점미 2018. 12. 6. 14:58



생성자와 new - https://opentutorials.org/course/743/6570



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

아래는 객체, 프로퍼티, 메소드를 생성한 예제이다.


var person = {}    //비어있는 객체를 만든다.

person.name = 'egoing';     //객체에 name프로퍼티를 만들고 'egoing'문자열을 넣는다는 뜻이

person.introduce = function(){        //introduce프로퍼티안에 메소드가 담겨있는 것이다.

    return 'My name is '+this.name;      //this는 메소드가 포함되어 있는 객체인 person이며 this.name은 person.name을 뜻한다.

}

document.write(person.introduce());






객체를 생성할 때 비어있는 객체가 아닌 결합되어 있는 객체를 만든 예제이다.


var person = {

    'name' : 'egoing',

    'introduce' : function(){

        return 'My name is '+this.name;

    }

}

document.write(person.introduce());







생성자

생성자(constructor)는 객체를 만드는 역할을 하는 함수다. 

아래는 함수가 객체를 만든 예제이다.


function Person(){}

var p = new Person(); //함수앞에 new를 붙이면 객체가 된다. p는 빈 객체가 된것이다.

p.name = 'egoing';

p.introduce = function(){

    return 'My name is '+this.name; 

}

document.write(p.introduce());





생성자 함수안에 this를 정의함으로써 초기화를 진행한다.

p1, p2일 때 각 각 this의 값이 달라지는 것을 확인 할 수 있다.


function Person(name){

    this.name = name;

    this.introduce = function(){

        return 'My name is '+this.name; 

    }   

} //함수를 정의

var p1 = new Person('egoing'); //함수앞에 new를 붙여서 person은 생성자가 되었다. 인자인 'egoing'은 person의 name으로 들어간다.

document.write(p1.introduce()+"<br />"); 

 

var p2 = new Person('leezche');

document.write(p2.introduce());