웹 실습

this이용과 단독적 인스턴스 생성 위한 요소

life... 2022. 4. 6. 05:36

 

 

함수안에서 사용이된 인자들을

property 사용하기 위해서는

this 사용해서 연결해주는 작업이 필요하다.

 

this를 이용해 단독적인 인스턴스를 만들려고하자.

function Song(singer,title,release){

this.singer=singer;

this.title=title;

this.release=release;

 

console.log(this);

}

 

const song1=Song();

문제상황발생!!

//우리는

단독적인 인스턴스를 만들고싶은 것인데

여기서 this 윈도우를 가리키고

윈도우 안에 singer 들어간다.

 

그러면 어떻게 단독적 인스턴스를 만드는가?

답은 new 이다.

 

new라는 키워드를 사용했을

this 어떤값을 보여주는지 확인해보면

 

function Song(singer,title,release){

this.singer=singer;

this.title=title;

this.release=release;

 

console.log(this);

}

 

const song1= new Song();

 

 

함수에 들어있는 인스턴스를

this 가리키게 된다.

 

new키워드가 없다면 위처럼 윈도우를 가리키게된다.

 

 

따라서 객체지향에서 함수 사용하려면

반드시 new키워드 써서 인스턴스화를해주어야한다.