나는 무엇이든 간단하게 표현하는 것을 좋아한다.
잘까먹기 때문에..
자 질문이 들어왔다.
화살표 함수란 무엇인가요?
이렇게 대답하면 된다. (면접 답변X)
현재 스코프에 있는 this를 이 함수의 this로 지정해주는 문법
this를 상속받는다고 생각하면 된다.
이것을 이해하려면 화살표 함수가 아닌 기본 함수는 어떻게 동작했는지를 알아야 한다.
일반 함수는 어떠한 경우에도 global 객체를 해당 함수의 this로 지정한다.
예시를 통해 이해해보자
const someObj = {
value: "awesome value!",
arrowFunc: function (arr) {
arr.forEach(() => {
arr.forEach(() => {
console.log("this.value is ", this.value);
});
});
},
notArrowFunc: function (arr) {
arr.forEach(function () {
arr.forEach(function () {
arr.forEach(function () {
arr.forEach(function () {
console.log("this.value is ", this.value);
});
});
});
});
}
}
someObj.arrowFunc([""]); // this.value is awesome value!
someObj.notArrowFunc([""]); // this.value is undefined
이와 같이 notArrowFunc 함수를 실행하면 someObj 객체에 있는 value값을 온전히 가져오지 못한다.
한번 js 파일의 최상단 위치에 global.value에 값을 지정하는 코드를 넣어보겠다.
global.value = "epic value!";
someObj.arrowFunc([""]); // this.value is awesome value!
someObj.notArrowFunc([""]); // this.value is epic value!
아래와 같은 결과가 나온다
추가적인 정보로 화살표 함수는 결국 this 바인드를 간편화 한 문법이라고 볼 수 있다!
아래는 모든 forEach에 bind를 추가한 예시다
const someObj = {
value: "awesome value!",
notArrowFunc: function (arr) {
arr.forEach(function () {
arr.forEach(function () {
arr.forEach(function () {
arr.forEach(function () {
console.log("this.value is ", this.value);
}.bind(this));
}.bind(this));
}.bind(this));
}.bind(this));
},
}
someObj.notArrowFunc([""]); // this.value is awesome value!
someObj에 있는 value가 정상적으로 출력된다.
최종 정리
지금까지 화살표 함수의 용도에 초점에 맞춘 설명을 하였다
이와 같이 화살표 함수는 현재 스코프에 있는 this를 새롭게 정의한 함수에도 가져와 재정의 해주는 역할을 한다.
나는 이를 "현재 스코프에 있는 this를 이 함수의 this로 지정해주는 문법" 이라고 정했다.
근데 뭔가 '체이닝'이라는 단어가 느껴진다..
나는 그래서 화살표 함수를 'this 체이닝' 이라고도 부르려고 한다!
'Knowledge > Node' 카테고리의 다른 글
[Node] 비동기 처리 vs 멀티 스레드 vs 멀티 프로세스 (속도 성능을 고려한 코드) (0) | 2024.11.02 |
---|---|
[Node] 배열 초기화 (0) | 2022.08.03 |
[Node/Express] 미들웨어의 종류 (0) | 2022.03.29 |
[Node/Express] set/get, use 정리 (0) | 2022.03.29 |
[Node] export & import / module.exports , exports & require( ) (0) | 2021.12.28 |