JavaScript 기본 상식 #3 (scope에 따른 this)
JavaScript 기본 상식 #3 (scope에 따른 this) JavaScript에서 "this"는 생각보다 복잡한 상황을 초래한다. 어떻게 보면 왜 그랬을까 싶기도 한데, 상황에 따른 복잡한 문제가 있는데, 모두 다룰 순 없고, 여기에서는, 익숙해지는 정도까지 진행해보고자 한다. 일반적으로 "this"는 scope는 "{}"에 기반한다고 이해하는 것이 보통은 편하다. console.log('What is this?, this); 결과는? (Chrome DevTools console) What is this? Window 여기 "Window"는 우리가 알고 있는 그 window이다. 그럼, 함수 내에서는 어떻게 표현되는지 확인해 보자! this.foo = 'window'; console.log('[Window Scope] What is foo?', this, this.foo); (function test1() { console.log('[Function Scope:Previous] What is foo?', this, this.foo); this.foo = 'global'; console.log('[Function Scope] What is foo?', this, this.foo); return { foo: 'local', bar: function () { console.log('[Function Scope:Inner] What is foo?', this, this.foo); } }; })().bar(); 결과는? (Chrome DevTools console) [Window Scope] What is foo? Window window [Function...
댓글
댓글 쓰기