From 92965f8e87fd21621591efe4e350fee89860dc4a Mon Sep 17 00:00:00 2001 From: lywoo00 <57310334+lywoo00@users.noreply.github.com> Date: Fri, 12 Dec 2025 14:56:09 +0900 Subject: [PATCH] =?UTF-8?q?this=20binding=203=EB=B2=88=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=20=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- this-binding/03_lyw.js | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 this-binding/03_lyw.js diff --git a/this-binding/03_lyw.js b/this-binding/03_lyw.js new file mode 100644 index 0000000..0684087 --- /dev/null +++ b/this-binding/03_lyw.js @@ -0,0 +1,51 @@ +/** + * ❓ 문제: this 바인딩 + 클로저 + 비동기 흐름까지 종합 예측하기 (중급) + * + * 출력 결과를 각 줄마다 예측하세요. + * 요구사항: + * 1) console.log가 총 5번 실행되는데, 순서와 값을 각각 예측할 것 + * 2) 왜 그런 결과가 나오는지 this 바인딩 / 클로저 / 마이크로태스크(Promise) 관점에서 설명 + * 3) 특히 setTimeout 내부 this, 화살표 함수 this, bind된 함수 this, call로 변경된 this 등 차이를 반드시 언급할 것 + */ + +var name = "Global"; + +const obj = { + name: "OBJ", + x: 10, + + getX() { + return this.x; + }, + + run() { + // 1) 클로저가 원본 this를 유지하지 않는 경우 + const fn1 = this.getX; + console.log("1:", fn1()); // 일반함수 this는 window객체 참조 = undefined + + // 2) call로 this를 즉시 변경 + console.log("2:", fn1.call(obj)); // call로 obj를 불러와서 this.x 는 obj의 x = 10 + + // 3) bind로 this 영구 고정 + const fn2 = this.getX.bind(this); + console.log("3:", fn2()); // getX에 this를 고정으로 obj 바인딩 = 10 + + // 4) setTimeout 전통 함수 → this 자동 바인딩 없음 + setTimeout(function () { + console.log("4:", this.name); // setTimeout은 this를 바이딩하지 않음 = Global + }, 0); + + // 5) Promise + 화살표 함수 → 상위 this를 캡처 + Promise.resolve().then(() => { + console.log("5:", this.name); // 비동기함수는 this를 바이딩하지 않지만 화살표함수는 this를 부모의 this를 가져옴 = OBJ + }); + }, +}; + +obj.run(); +// 실행결과 +// 1: undefined +// 2: 10 +// 3: 10 +// 4: Global +// 5: OBJ