상황에 딸라 달라지는 this
a. 함수 vs 메서드
b. this의 할당
// CASE1 : 함수
// 호출 주체를 명시할 수 없기 때문에 this는 전역 객체를 의미해요.
var func = function (x) {
console.log(this, x);
};
func(1); // Window { ... } 1
// CASE2 : 메서드
// 호출 주체를 명시할 수 있기 때문에 this는 해당 객체(obj)를 의미해요.
// obj는 곧 { method: f }를 의미하죠?
var obj = {
method: func,
};
obj.method(2); // { method: ƒ } 2
즉 case1은 함수 자체를 호출하기때문에 this는 전역객체
case2는 호출의 주체가 있기때문에 this는 해당객체인 obj를 의미함
c. 함수로서의 호출과 메서드로서의 호출 구분 기준: .[]
.으로 호출하든 []로 호출하든 결과는 같다.
var obj = {
method: function (x) { console.log(this, x) }
};
obj.method(1); // { method: f } 1
obj['method'](2); // { method: f } 2
d. 메서드 내부에서의 this
this에는 호출을 누가 했는지에 대한 정보가 담긴다
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