Function과 Arrow Function에서 this의 차이

3864 단어 JavaScriptJavaScript

Function

일반 function안의 this는 자신을 가장 마지막으로 품고 있는 scope로 항상 변하는 특징이 있다.

function callFunc(){
  return {
    foo : 25,
    bar : function(){
      console.log(this.foo);
    }
  }
}

callFunc.call({foo:100}).bar(); // 25

Arrow Function

Arrow Function은 익명함수 선언 방식으로 간결하게 코드를 작성할 수 있다.
보통 ( ) => { }의 모양이다. this와 arguments를 바인딩 하지 않는다.

function callFunc(){
  return {
    foo : 25,
    bar : () => {
      console.log(this.foo);
    }
  }
}

callFunc.call({foo:100}).bar(); // 100

화살표 함수 안에서의 this는 callFunc안의 this를 따르게 된다. 즉, 현재 환경의 this를 따르게 하고 싶을 때 화살표 함수를 사용하면 된다.

좋은 웹페이지 즐겨찾기