전역 공간에서의 this
1. 전역 공간에서 this는 전역 객체를 가리킴
2. window(브라우저 환경), global(node 환경)
console.log(this); console.log(window); console.log(this === window); //true
1. 기준 : 독립성
2. 함수 : 그 자체로 독립적인 기능을 수행
3. 메서드 : 자신을 호출한 대상 객체에 관한 동작을 수행
var func = function (x) { console.log(this, x); }; func(1); // Window { ... } 1 var obj = { method: func,@2022년 11월 16일 this2}; obj.method(2); // { method: f } 2
var obj = { method: function (x) { console.log(this, x) } }; obj.method(1); // { method: f } 1 obj['method'](2); // { method: f } 2
var obj = { methodA: function () { console.log(this) }, inner: { methodB: function() { console.log(this) }, } }; obj.methodA(); // this === obj obj['methodA'](); // this === obj obj.inner.methodB(); // this === obj.inner obj.inner['methodB'](); // this === obj.inner obj['inner'].methodB(); // this === obj.inner obj['inner']['methodB'](); // this === obj.inner
1. 어떤 함수를 함수로서 호출할 경우, this는 지정되지 않음(호출 주체가 없으므로)
2. 실행컨텍스트를 활성화할 당시 this가 지정되지 않은 경우, this는 전역 객체를 바
라봄
3. 따라서, 함수로서 ‘독립적으로’ 호출할 때는 this는 전역 객체
1. 메서드의 내부라고 해도, 함수로서 호출한다면 this는 전역 객체
var obj1 = { outer: function() { console.log(this); var innerFunc = function() { console.log(this); } innerFunc(); var obj2 = { innerMethod: innerFunc this3}; obj2.innerMethod(); } }; obj1.outer();
2. this 바인딩에 관해서는 함수를 실행하는 당시의 주변 환경(메서드 내부인지, 함수
내부인지)은 중요하지 않고, 오직 해당 함수를 호출하는 구문 앞에 점 또는 대괄호
표기가 있는지가 관건임!