on
[자바스크립트] this 사용법 및 개념
[자바스크립트] this 사용법 및 개념
728x90
이번 시간에는 자바스크립트 this
사용법과 개념에 대해서 알아보도록 하겠습니다.
this 사용법
자바스크립트 객체안에 객체 프로퍼티로 할당되어 존재하는 함수를
매서드(METHOD)라고 합니다.
아래의 객체의 bebe, nana의 매서드는 color가 됩니다.
//매서드 color의 this는 해당객체인 bebe를 가르킨다. const bebe = { name : "bebe", age : 1, color : function(){ console.log(`${this.name}의 색깔은 검은색 입니다.`) } } //매서드 color의 this는 해당객체인 nana를 가르킨다. const nana = { name : "nana", age : 1, color : function(){ console.log(`${this.name}의 색깔은 노란색 입니다.`) } } console.log(bebe.color()); //검은색 입니다. console.log(nana.color()); //노란색 입니다.
주의사항
화살표 함수는 일반 함수와 달리 자신만의 this를 가지지 않습니다.
따라서 내부에서 this를 사용하게되면 그 this는 외부에서 값을 가져옵니다.
const bebe = { name : "bebe", age : 1, color : ()=>{ console.log(`${this.name}의 색깔은 검은색 입니다.`) //화살표 함수는 this를 가지고 있지 않기 떄문에 사용시 "전역객체"인 window를 가르킵니다. } } console.log(bebe.color()); //this가 bebe가 아니라서 값이 안나옴.
this.name의 값이 없는 것으 볼수 있음.
이상으로 this 사용법에 대해서 알아보았습니다.
반응형
그리드형
from http://bebeya.tistory.com/1551 by ccl(A) rewrite - 2021-09-13 16:27:03