Web/JavaScript

4.4 - 화살표 함수와 일반 함수의 this

페프 2024. 2. 28. 05:00

화살표 함수  VS  일반 함수

화살표 함수의 this는 호출된 함수를 둘러싼 실행 컨텍스트를 가리킨다.

-> 함수가 호출될 때의 환경(화살표 함수가 선언 될 떄)의 this 값을 유지한다.

일반 함수의 this는 새롭게 생성된 실행 컨텍스트를 가리킨다.
-> 새롭게 생긴 실행 콘텍스트를 가리킨다. 

예시)

const o = {
    method() {
        console.log("context : ", this)          
        let f1 = function(){
            console.log("[fi] this : ", this)  
        }
        
        let f2 = () =>
            console.log("[f2] this : ", this)
        f1()                    
        f2()                    
    },
}
o.method()
03. method 함수 안에서의 this는 객체(o)를 가리킨다.
04 ~ 06. f1 함수는 일반 함수 선언
07 ~ 08. 2 함수는 화살표 함수로 선언
09. 바인딩된 컨텍스트가 없으므로 this는 global를 가리킨다.
10. 함수 컨텍스트가 호출하는 환경 = 객체(o) 를 가리킨다.

 

정리

  • 화살표 함수의 this는 정해지면 바꿀 수 없다.
  • call, bind, apply를 사용해도 바뀌지 않는다.
  • setTimeout 등 this가 바뀌는 상황에서 유용하다.

화살표 함수와 dynamic binding

window.name = 'Daniel'
let o = { neme : "Kim"}

let arrowFunction = (prefix) => console.log(prefix + this.name)

arrowFunction('Dr. ')
arrowFunction.bind(o)('Dr. ')
arrowFunction.call(o,'Dr. ')
arrowFunction.apply(o, ['Dr. '])

 

06. console에 'Dr. Daniel' 이란 결과가 나온다.
07. console에 'Dr. Daniel' 이란 결과가 나온다.
08. console에 'Dr. Daniel' 이란 결과가 나온다.
09. console에 'Dr. Daniel' 이란 결과가 나온다.