티스토리 뷰

현상

var mySet = new Set();
['bar', 'baz'].forEach(mySet.add);

이 현상은 꼭 Set이어야 하는 것은 아니고, 콜백 내부에서 this를 사용하고 있는 케이스에서 문제가 된다.
forEach문이나 map에는 첫번째 인자로 콜백을 넘겨주고 두 번째인자로 this를 넘겨주도록 되어있는데, 만약 값을 넘겨주지 않으면 두 경우 모두 undefined 로 설정된다. 그러므로 콜백으로 넘겨준 메서드 내에서 this가 사용되고 있는 경우, 참조하는 this가 undefined가 되어 정상적으로 실행되지 않는다.

해결 방법

  1. 명시적인 바인딩
  2. var mySet = new Set(); ['bar', 'baz'].forEach(mySet.add.bind(mySet));
  1. Arrow 함수 사용화살표 함수의 this는 상위 스코프의 this를 참조한다. (참고 - this 정리 포스팅)
  2. var mySet = new Set(); ['bar', 'baz'].forEach(element => mySet.add(element));

Ref

https://stackoverflow.com/questions/37199019/method-set-prototype-add-called-on-incompatible-receiver-undefined
https://stackoverflow.com/questions/63624124/how-does-this-keyword-work-in-map-and-call
https://qvault.io/javascript/javascript-map-function-explained-a-deep-dive/

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함