Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions this-binding/02_lyw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//❓ 답해야 하는 것
//각 줄의 출력 결과 (1~5)는 무엇인가?
//왜 그렇게 되는지 this와 클로저 관점에서 설명하시오.
//특히 아래 4개 상황에서 this가 어떻게 바인딩되는지 설명하시오:
//일반 함수 호출, 메서드 호출, bind로 고정한 함수, this가 없는 상황에서의 화살표 함수

var name = "Global";

const counter = {
name: "Counter",
value: 0,
inc() {
this.value++;
return this.value;
},
run() {
console.log("1:", this.inc()); // counter가 run을 호출 -> this는 counter, this가 inc를 호출 -> this는 counter = 출력 결과 1

const fn1 = this.inc;
const fn2 = this.inc.bind(this);

setTimeout(function () {
console.log("2:", this.inc ? this.inc() : this.name); // setTimeout은 전역객체(window)를 참조 -> winsodw에 inc가 없음 = 출력 결과 'Global'
}, 0);

setTimeout(() => {
console.log("3:", this.inc()); // setTimeout은 전역객체(window)를 참조하지만 화살표함수에는 this가 없음 -> this는 함수를 감싸고있는 부모를 바라봄 -> 1번에서 vlaue++ 됨 -> 같은 객체를 참조 = 출력 결과 2
}, 0);

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.

머지웨안해요?

}
return x;
});

(function () {
console.log("5:", this.inc ? this.inc() : this.name); // 즉시실행 함수는 this가 전역객체(window)를 카리킴 = 출력 결과 'Global'
})();
},
};

counter.run();
/*
실행 순서
1: 1
4: Global
5: Global
2: Global
3: 2
*/