본문 바로가기

프론트엔드 공부/javscript

일반함수와 화살표함수에서 this 정의 차이점

setTimeOut이나 setInterval 같은 함수 사용시 콜백으로 화살표함수 사용하는것이 더 활용서이 뛰어나다

//this 일반함수, 화살표함수 차이
//일반(normal) 함수는 호출 위치에 따라 this 정의 !!
//화살표(arrow) 함수는 자신이 선언된 함수 범위 내에서 this 정의 !!

function User(name){
  this.name = name;
}

User.prototype.normal = function(){
  console.log(this.name);
}
User.prototype.arrow = () => {
  console.log(this.name);
}
//객체생성자함수
const mag = new User('phter');

mag.normal(); //pheter
mag.arrow();// undefined

//***화살표함수의 this 활용
const timer = {
  name:'minji',
  timeout:function(){
    setTimeout(()=>{
      console.log(this.name);
      //function(){ console.log(this.name)}; //setTimeout 위치 내에서 this가 없으므로 udefined
    },2000)
  }
}
timer.timeout(); //2초뒤 실행