대부분의 상황에서 this는 쉽게 설명하면 자신을 호출한 놈을 가리킨다.
const test = {
text: "test",
printThis: function () {
console.log(this);
},
};
function printThis() {
console.log(this.text);
}
test.printThis();
// output: test
printThis();
// output: Window object
위 상황에서 test.printThis()는 test 객체에 의해 호출되었으므로, this가 test 객체를 가리킨다.
반면 전역 공간에서는 this가 window 객체를 가리킨다. 이는 strict mode를 사용하지 않을 때, this가 가리키는 기본값이다.
전역 공간에서 this가 window 객체를 가리켰듯이 this가 호출한 놈을 가리키지 않는 예외 상황이 있다.
thisthis : undefinedthis화살표 함수의 this는 렉시컬 컨텍스트를 감싼 상위 스코프의 this를 물려받는다.
렉시컬 스코프란 함수를 어디에서 선언했는지에 따라서 상위 스코프가 결정되는 것을 말한다.
※ 함수가 어디에서 호출되었는지에 따라 결정되는 것은 다이나믹 스코프라고 한다.
const foo = {
name: "foo",
printText: function() {
console.log(this.name)
}
}
foo.printText()
// output: foo
this는 this를 감싸고 있는 foo 객체를 가리킨다.const foo = {
name: "foo",
printText: () => {
console.log(this);
}
}
foo.printText();
// output: Window 객체
화살표 함수에서는 렉시컬 컨텍스트의 상위 스코프로부터 this를 물려 받는다고 했다.
this인 window 객체가 반환된다.즉 다음과 같은 상황에서는 화살표 함수 사용에 주의 해야한다.
eventListener의 callback 함수 : 원래는 리스닝하는 요소를 가리키지만 화살표 함수에서는 window가 되어버린다.bind 메서드ES5부터는 bind 메서드가 도입되어 this가 원하는 객체를 가리키도록 묶어줄 수 있다.
const test = {
text: "test",
printThis: function () {
console.log(this.text);
},
};
function printThis() {
console.log(this.text);
}
test.printThis();
// output: test
const bindedPrintThis = printThis.bind(test); // 바인딩
bindedPrintThis();
// output: test
bind 메서드는 함수와 인자로 받은 객체가 바인딩 한 함수를 반환한다.
해당 함수에서 this를 사용하면 바인딩 되어있는 객체를 가리키게 된다.
주의할 점은 한번 바인딩된 객체는 바꿀 수 없다는 것이다. 다시 bind 메서드를 사용해도 처음 바인딩 된 객체가 출력된다.
잘 읽었습니다. 좋은 정보 감사드립니다.