- 화살표 함수의 this는 호출된 함수를 둘러싼 실행 컨텍스트를 가리킨다.
- 일반 함수의 this는 새롭게 생성된 실행 컨텍스트를 가리킨다.
아래의 코드를 예시로 보면, f1은 일반함수, f2는 화살표 함수로 선언되어 있다.
const o = {
method(){
console.log("context : ", this) // o
let f1 = function () {
console.log("[f1] this : ", this)
}
let f2 = () =>
console.log("[f2] this : ", this)
f1() // global
f2() // o
},
};
o.method()
아래의 코드는 화살표 함수가 활용되는 예시이다.
window.name = "Hannah"
let o = { name : "K" }
let arrowFunction = (prefix) => console.log(prefix + this.name)
arrowFunction("Dr. ") // Dr. Hannah
arrowFucntion.bind(o)("Dr. ") // Dr. Hannah
arrowFucntion.call(o, "Dr. ") // Dr. Hannah
arrowFucntion.apply(o, ["Dr. "]) // Dr. Hannah
위처럼 bind와 call, apply를 사용해도 화살표 함수로 선언되어 있으면 this 값이 바뀌지 않음을 알 수 있다.