이 포스트는 모던자바스크립트를 공부하고 정리한 것입니다.
화살표함수는 멋있다.
const add = (a,b) => a + b;
근데 이거 function 놔두고 왜 사용하는 걸까?
화살표 함수는 콜백함수 내부 this가 전역객체를 바인딩하는 문제를 해결하기 위해 사용한다.
화살표 함수와 일반 함수의 큰 차이는 화살표 함수는
this, arguments, super, new.target의 바인딩을 갖지 않는다.
가장 큰 차이점은 this다. this는 일반함수와 화살표 함수에서 다르게 동작한다.
JS에서 this는 타언어와 다르다. this 바인딩은 함수가 어떻게 호출되었는지에 따라 동적으로 결정된다.
함수를 정의할 때 this에 바인딩할 객체가 정적으로 결정되지 않는다.
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
return arr.map(function (item) {
return this.prefix + item; // Cannot read properties of undefined (reading 'prefix')
});
}
}
const prefixer = new Prefixer("-webkit-");
console.log(prefixer.add(["a", "b"]));
이 코드는 동작하지 않는다. map함수 인자로 전달한 콜백함수 내부에서 this는 undefined를 가리킨다.
따로 바인딩 하지 않는이상 일반함수 내부 this는 window 전역객체를 가리킨다.
물론 화살표함수를 사용하지 않고 이 문제를 해결할 방법은 많다.
add 메소드를 호출한 객체를 가리키는 this를 저장하고 사용
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
const that = this;
return arr.map(function (item) {
return that.prefix + item;
});
}
}
bind 메소드를 사용
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
return arr.map(function (item) {
return this.prefix + item;
}.bind(this));
}
}
화살표 함수 이용
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
return arr.map((ele) => this.prefix + ele);
}
}
화살표 함수는 함수 자체의 this 바인딩을 갖지 않는다.
화살표 함수 내부 this는 상위 스코프 체인을 타고 올라가 this를 참조한다.
이를 lexical this라 한다.
화살표 함수가 중첩됬다면 상위 화살표 함수 this도 바인딩된 값이 없으므로
스코프 체인을 타고 올라가 가장 가까운 this를 참조한다.
(function () {
const f1 = () => {
const f2 = () => {
console.log(this);
};
return f2;
};
f1()();
}.call({ x: 23 }));
화살표 함수가 전역에 쓰였다면 this는 전역객체를 가리킨다.
arguments
화살표 함수는 arguments 프로퍼티를 생성하지 않는다.
const test = () => {
console.log(arguments); // error
};
function test(){
console.log(arguments);
}
test([1, 2, 3]);
이벤트 핸들러
addEventListener 는 콜백함수 내부 this는 자기 자신으로 바인딩한다.
document.querySelector(".btn").addEventListener("click", (e) => {
console.log(this); // window
});
document.querySelector(".btn").addEventListener("click", function(e) {
console.log(this); // btn
});
'JavaScript' 카테고리의 다른 글
Syntax Sugar 정리 (0) | 2022.04.20 |
---|---|
이벤트 버블링, 캡쳐링, 위임 (0) | 2022.03.11 |
함수 선언식 vs 함수 표현식 (0) | 2021.12.20 |
let, const 블록레벨 스코프 (0) | 2021.10.09 |
댓글