Skip to content

문제2 풀이 - #7

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

문제2 풀이#7
lywoo00 wants to merge 1 commit into
mainfrom
feat/lyw-this-binding-02

Conversation

@lywoo00

@lywoo00 lywoo00 commented Dec 11, 2025

Copy link
Copy Markdown

Summary by CodeRabbit

문서

  • JavaScript 예제 파일이 추가되어 다양한 상황에서의 this 바인딩 동작을 시연합니다. 메서드 호출, 타이머 콜백, 화살표 함수, 배열 메서드, 즉시 실행 함수 등 여러 시나리오에서의 동작 방식을 포함합니다.

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

@lywoo00
lywoo00 requested a review from yujinimda December 11, 2025 07:11
@coderabbitai

coderabbitai Bot commented Dec 11, 2025

Copy link
Copy Markdown

Walkthrough

this-binding/02_lyw.js 파일을 추가하여 JavaScript의 다양한 맥락에서 this 바인딩이 어떻게 작동하는지 보여줍니다. 코드는 메서드 호출, 바인딩된 함수, setTimeout, 화살표 함수, Array.map 콜백, IIFE 등 여러 this 바인딩 시나리오를 시연합니다.

Changes

Cohort / File(s) 변경 요약
this-binding 데모 파일
this-binding/02_lyw.js
새로운 파일 추가: counter 객체와 run 메서드를 정의하여 직접 메서드 호출, 바인딩된/바인딩 해제된 함수, setTimeout 일반 함수 및 화살표 함수, Array.map 콜백, IIFE 등 다양한 this 바인딩 시나리오를 시연

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8분

  • 확인 사항:
    • this 바인딩 시나리오의 정확성 검증 (메서드 호출, bind, setTimeout, 화살표 함수)
    • 예상 실행 순서 및 출력값 주석의 정확성 확인
    • 코드 실행 결과가 주석에 명시된 대로 일치하는지 테스트

Possibly related PRs

  • Implement counter with various this binding examples #3: 거의 동일한 counter 객체 구조와 동일한 this 바인딩 사례(메서드 호출, 바인딩된 함수, setTimeout, Array.map, IIFE)를 정의하는 예제 파일을 추가합니다.
  • docs: 03 문제 추가 #5: this 바인딩 예제 파일(03.js)을 추가하며, 메서드 참조 저장, bind/call 사용, setTimeout, 화살표 함수 등 동일한 패턴을 구현합니다.

Suggested labels

enhancement

Poem

🐰 this는 가르킬 것 많네요,
바인딩의 마법을 보여주는 파일,
화살표, 타이머, 메서드의 춤,
전역과 지역의 경계를 넘으며,
학습자의 눈을 밝혀주는 빛이 되리! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive 제목 '문제2 풀이'는 변경사항의 주요 내용인 this 바인딩 관련 코드 예제 추가를 직접적으로 설명하지 못하고 있어 구체성이 부족합니다. 제목을 'this 바인딩 컨텍스트별 동작 예제 추가' 또는 '02_lyw.js: this 바인딩 시나리오 데모' 같이 더 구체적으로 수정하는 것을 권장합니다.
✅ 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-02

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.

@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: 0

🧹 Nitpick comments (3)
this-binding/02_lyw.js (3)

7-8: 실행 환경(브라우저 전역 / Node / 모듈 여부)을 명시해 두면 좋겠습니다.

이 코드는 브라우저의 non‑strict 전역 스크립트를 전제로 해야 var name = "Global"이 전역 객체 프로퍼티가 되고, 아래에서 일반 함수 호출 시 this === window가 되어 주석과 동일한 결과가 나옵니다. Node.js 파일이나 <script type="module"> 환경에서는 thisname의 동작이 달라질 수 있으니, 사용하는 실행 환경을 주석이나 README에 한 줄 정도 명시해 두면 혼동을 줄일 수 있습니다.


19-20: fn1 / fn2가 실제로 사용되지 않아 bind 사례가 충분히 드러나지 않습니다.

문제 지문에 “bind로 고정한 함수” 상황도 설명하라고 되어 있는데, 현재는 fn2 = this.inc.bind(this)까지만 있고 일반 함수 참조인 fn1과의 차이가 콘솔 결과로는 나타나지 않습니다. 예를 들어 fn1()fn2()를 각각 한 번씩 호출해서 로그를 남기거나, 최소한 주석으로 “fn1은 일반 함수 호출이라 this가 전역으로 떨어지고, fn2는 this가 counter로 고정된다”는 설명을 추가하면 학습용 예제로 더 명확해질 것 같습니다.


22-39: setTimeout, map 콜백, IIFE에 대한 주석을 this 규칙 관점으로 조금 더 정리하면 좋겠습니다.

지금은 “setTimeout은 전역객체를 참조”, “map의 콜백함수는 전역객체를 가리킴”, “즉시실행 함수는 this가 전역객체를 가리킴”처럼 API별로 다르게 표현되어 있는데, 세 경우 모두 공통적으로 “base 객체 없이 호출된 일반 함수(슬로피 모드)라서 this가 전역 객체로 fallback 된다”는 규칙으로 설명할 수 있습니다. 이 관점을 중심으로 주석을 정리하면 2, 4, 5번 출력이 모두 같은 this 규칙에서 나온 결과라는 점이 더 잘 드러날 것 같고, winsodw, vlaue, 카리킴 같은 오타도 함께 정리해 두면 가독성이 좋아집니다.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ff0af30 and 3f9bd83.

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

16-41: run 안에서 this 바인딩과 실행 순서를 단계별로 보여주는 구조는 잘 잡혀 있습니다.

메서드 호출(1번), setTimeout의 일반 함수/화살표 함수(2, 3번), 배열 메서드 콜백과 IIFE(4, 5번)를 한 흐름 안에 배치해서 this가 어떻게 달라지는지 한 번에 비교할 수 있어서 학습용 예제로 적절해 보입니다.


45-50: 로그 결과와 실행 순서 정리가 브라우저 환경 기준으로 잘 맞습니다.

동기 코드에서 1 → 4 → 5가 먼저 찍히고, 그 다음 이벤트 루프에서 0ms 타이머들이 등록 순서대로 2 → 3 순으로 실행된다는 점을 주석으로 정리해 둔 부분이 이해에 큰 도움이 됩니다.

Comment thread this-binding/02_lyw.js

const arr = [1, 2, 3].map(function (x) {
if (x === 2) {
console.log("4:", this.inc ? this.inc() : this.name); // map의 콜백함수는 전역객체(window)를 카리킴 = 출력 결과 'Global'

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.

Array.prototype.map의 콜백에서 this는 전역(window)이 아니라고 합니다..!
단지 “map 콜백은 기본적으로 this를 bind하지 않는다”가 맞는 표현이라고 하네용

map은 콜백 함수 내부에 this를 바인딩하지 않는다.
thisArg를 주지 않으면 strict mode에서는 undefined이고,
브라우저 non-strict에서는 undefined가 window로 변환된다.
그래서 window.name → "Global"이 출력된다.
라고 합니다..!

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.

결론: map이 setTimeout처럼 this를 바인딩하지 않는건지 알았는데
설정은 안했을 뿐이었다

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

리뷰 감사합니다^^

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