키워드 this

lbr·2022년 7월 10일
0

this

일반(Normal) 함수는 호출 위치에 따라 this 정의!

화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의!

객체에서의 this

const heropy = {
 name: 'Heropy',
 normal: function () { // 일반 함수
  console.log(this.name); 
 },
 arrow: () => { // 화살표 함수
 	console.log(this.name);
 }
}
heropy.normal();
heropy.arrow();

결과

Heropy // heropy.normal();의 결과
undefined // heropy.arrow();의 결과
const heropy = {
 name: 'Heropy',
 normal: function () { // 일반 함수
  console.log(this.name); 
 },
 arrow: () => { // 화살표 함수
 	console.log(this.name);
 }
}
heropy.normal();
heropy.arrow();

const may = {
 name: 'Amy',
 normal: heropy.normal,
 arrow: heropy.arrow
}
amy.normal();
amy.arrow();

결과

Amy // amy.normal();의 결과
undefined // amy.arrow();의 결과
  • 일반함수에서의 this는 호출위치에서 정의됩니다.
  • amy.normal(); 로 호출했으므로 this는 호출된 위치인 amy가 됩니다.

이 차이점을 잘 알고 있어야 JavaScript Class 에서 일반함수로 만들지, 화살표 함수로 만들지를 명확하게 결정할 수 있습니다.
왜냐하면JavaScript Class에서는 this를 매우 많이 사용하기 때문입니다.

prototype을 사용하는 생성자 함수에서 this의 정의

function User(name) {
  this.name = name;
}
User.prototype.normal = function () {
 console.log(this.name); 
}
User.prototype.arrow = () => {
 console.log(this.name);
}

const heropy = new User('Heropy');

heropy.normal();
heropy.arrow();

결과

Heropy // heropy.normal();
undefined // heropy.arrow();

다른 예

const timer = {
 name: 'Heropy!!',
 timeout: function () {
   //setTimeout(함수, 시간)
   setTimeout(function () {
   	console.log(this.name);
   }, 2000);
 }
}
timer.timeout();

결과

undefined // timer.timeout();의 결과
const timer = {
 name: 'Heropy!!',
 timeout: function () {
   //setTimeout(함수, 시간)
   setTimeout( () => {
   	console.log(this.name);
   }, 2000);
 }
}
timer.timeout();

결과

Heropy!! // timer.timeout();의 결과
  • 타이머 함수를 사용할 때는 콜백으로 일반함수보다는 화살표함수를 사용하는 것이 더 활용도가 높습니다.

참고할 블로그

1

0개의 댓글