Skip to content

this binding 3번 문제 풀이 - #11

Open
lywoo00 wants to merge 1 commit into
mainfrom
feat/lyw-this-binding-03
Open

lywoo00 wants to merge 1 commit into
mainfrom
feat/lyw-this-binding-03

Conversation

@lywoo00

@lywoo00 lywoo00 commented Dec 12, 2025

Copy link
Copy Markdown

Summary by CodeRabbit

  • 문서
    • JavaScript this 바인딩, 클로저, 비동기 동작을 보여주는 예제 코드 추가. 다양한 시나리오에서의 동작을 설명하는 인라인 주석 포함.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 12, 2025

Copy link
Copy Markdown

코드 리뷰 분석

Walkthrough

JavaScript의 this 바인딩, 클로저, 비동기 동작을 다섯 가지 시나리오로 보여주는 교육용 예제 파일이 추가되었습니다. 메서드 분리, call 호출, bind 사용, setTimeout, 그리고 Promise.then에서의 this 컨텍스트 변화를 실제 콘솔 출력으로 설명합니다.

Changes

Cohort / File(s) 변경 요약
This 바인딩 예제 추가
this-binding/03_lyw.js
JavaScript의 this 바인딩 동작을 5가지 사례로 설명하는 자체 포함 스크립트 파일 추가: 메서드 분리 시 undefined, call 메서드 적용, bind를 통한 영구 바인딩, setTimeout의 전역 this, Promise의 화살표 함수에서 외부 this 캡처

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

  • 단일 파일 추가로 제한된 범위
  • 교육용 예제로서 간단한 로직 구조
  • 인라인 주석으로 각 사례 설명 제공

Possibly related PRs

  • 03 문제 답변 제출 #8: 동일한 this 바인딩 예제(getX/run 동작, call/bind/setTimeout/Promise 시퀀스)를 추가하는 PR
  • Yujin/refactor 02 #9: 동일한 this-binding/03 예제 파일을 수정하는 PR(getX, run, 분실된 바인딩, call/bind, setTimeout, Promise.then)
  • docs: 03 문제 추가 #5: 동일한 this 바인딩 예제(5가지 로그 사례 포함)를 추가하는 PR

Suggested labels

enhancement

Poem

🐰 이 바인딩의 미로를 탈출하려면,
Call과 bind의 마법을 배워야 하네요!
화살표 함수가 구원의 손길을 내밀고,
다섯 가지 진실이 콘솔에 속삭여요.
자, 이제 this의 정체를 알게 되셨나요? 🎯

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive PR 제목이 변경 내용과 관련이 있으나, 너무 모호하고 구체적이지 않습니다. '3번 문제 풀이'는 특정 상황에서만 의미가 있으며, 브랜치를 보지 않으면 실제 변경 내용(this 바인딩 예제 추가)을 명확히 파악하기 어렵습니다. 제목을 'Add this binding example with closures and async behavior' 같이 더 구체적이고 설명적으로 변경하여, 깃 히스토리를 볼 때 실제 변경 내용을 명확히 알 수 있도록 하는 것이 좋습니다.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/lyw-this-binding-03

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@lywoo00
lywoo00 requested a review from yujinimda December 12, 2025 05:56

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
this-binding/03_lyw.js (1)

22-28: “클로저가 this를 유지하지 않는다”는 설명이 부정확합니다(핵심은 call-site/메서드 분리).
const fn1 = this.getX;로 “메서드 분리”가 일어나 호출 시점에 receiver가 없어져 this가 달라지는 게 포인트라, 클로저로 설명하면 오해 소지가 있습니다.

-    // 1) 클로저가 원본 this를 유지하지 않는 경우
+    // 1) 메서드 분리(호출 위치 변화)로 this 바인딩이 깨지는 경우
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc6a1f8 and 92965f8.

📒 Files selected for processing (1)
  • this-binding/03_lyw.js (1 hunks)
🔇 Additional comments (1)
this-binding/03_lyw.js (1)

13-43: 학습 시나리오 구성 자체는 좋습니다(분리/call/bind/타이머/Promise를 한 번에 비교).
다만 위의 “실행 순서”와 “런타임 전제”만 정리되면 예제 완성도가 확 올라갈 것 같습니다.

Comment thread this-binding/03_lyw.js
Comment on lines +11 to +12
var name = "Global";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

this/name 결과가 런타임(브라우저/Node, module/strict)에 따라 달라져 예제가 비결정적입니다.

  • fn1()는 ES module/strict에선 this === undefinedthis.x 접근 시 예외가 날 수 있습니다.
  • var name = "Global"은 Node에서 globalThis.name을 보장하지 않고, setTimeout 콜백의 this도 브라우저/Node에서 다릅니다.
    학습용이면 “브라우저의 classic script(비-module) 기준” 같은 전제를 상단에 명시하거나, globalThis를 사용해 전역 값을 분리해서 보여주는 쪽이 안전합니다.
-var name = "Global";
+globalThis.name = "Global";
-    setTimeout(function () {
-      console.log("4:", this.name); // setTimeout은 this를 바이딩하지 않음 = Global
-    }, 0);
+    setTimeout(function () {
+      // 런타임별로 this가 달라질 수 있어 globalThis도 함께 보여주는 편이 안전
+      console.log("4:", this && this.name, "(globalThis:", globalThis.name + ")");
+    }, 0);

Also applies to: 21-41

🤖 Prompt for AI Agents
In this-binding/03_lyw.js around lines 11-12 (and similar cases at 21-41), the
example relies on environment-dependent behavior of `this` and `var name` which
makes the output non-deterministic across strict/module/Node/browser contexts;
either (A) explicitly state at the top that the examples assume "browser classic
script (non-module) environment" so readers know the precondition, or (B) make
the code deterministic by replacing global `var name = "Global"` with
`globalThis.name = "Global"` (or reference `globalThis` for the global value)
and change functions that rely on implicit `this` to use explicit receivers
(pass the object or use `.call/.bind`) or read from `globalThis` so behavior is
consistent across environments; apply the same change to the similar examples in
lines 21-41.

Comment thread this-binding/03_lyw.js
Comment on lines +33 to +41
// 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
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

기대 출력 순서가 틀립니다(마이크로태스크가 타이머보다 먼저 실행).
Promise.then(microtask)은 현재 콜스택 종료 직후 setTimeout(..., 0)(macrotask)보다 먼저 실행되므로, 실제 순서는 1,2,3,5,4가 됩니다. 주석의 “4 다음 5”는 수정 필요합니다.

-// 4: Global
-// 5: OBJ
+// 5: OBJ
+// 4: Global

Also applies to: 46-51

Comment thread this-binding/03_lyw.js
console.log("4:", this.name); // setTimeout은 this를 바이딩하지 않음 = Global
}, 0);

// 5) Promise + 화살표 함수 → 상위 this를 캡처

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

녀석아
프로미스는 마이크로태스큐
셋타임아웃은 태스크큐

그래서 마이크로 > 테스크 이렇게 실행된다

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants