this 바인딩은 JavaScript에서 매우 중요한 개념 중 하나로, 함수나 메서드가 호출되는 방식에 따라 this가 가리키는 값(즉, this의 바인딩)이 결정됩니다. this의 값은 함수가 호출되는 실행 컨텍스트에 의해 결정되며, 다양한 방식으로 함수가 호출될 때 this가 어떻게 결정되는지를 이해하는 것은 JavaScript 프로그래밍에 있어 필수적입니다.
this전역 실행 컨텍스트에서 this는 전역 객체를 가리킵니다. 브라우저에서는 window 객체가 전역 객체이며, Node.js 환경에서는 global 객체가 해당됩니다.
console.log(this === window); // 브라우저에서는 true
this기본적으로 함수 내부에서의 this는 전역 객체를 가리킵니다. 하지만, 엄격 모드('use strict')에서는 this가 undefined로 설정됩니다.
function showThis() {
console.log(this);
}
showThis(); // 일반 모드에서는 window(브라우저) 또는 global(Node.js), 엄격 모드에서는 undefined
this객체의 메서드로 함수를 호출할 때, this는 그 메서드를 호출한 객체에 바인딩 됩니다.
const obj = {
method: function() {
console.log(this);
}
};
obj.method(); // this는 obj를 가리킵니다.
thisnew 키워드를 사용하여 생성자 함수를 호출하면, this는 새로 생성된 객체에 바인딩 됩니다.
function Constructor() {
this.value = "some value";
}
const instance = new Constructor();
console.log(instance.value); // "some value"
call, apply, bind 메서드에 의한 명시적 바인딩call, apply, bind 메서드를 사용하면 함수 호출 시 this의 값을 명시적으로 지정할 수 있습니다.
function showThis(a, b) {
console.log(this, a, b);
}
const obj = {name: "Explicit"};
showThis.call(obj, 1, 2); // obj, 1, 2
showThis.apply(obj, [1, 2]); // obj, 1, 2
const bound = showThis.bind(obj, 1, 2);
bound(); // obj, 1, 2
this화살표 함수는 일반 함수와 달리 자신만의 this 바인딩을 생성하지 않습니다. 대신, 화살표 함수는 자신이 선언된 렉시컬 컨텍스트의 this를 상속받습니다.
const obj = {
method: function() {
const arrowFunc = () => console.log(this);
arrowFunc();
}
};
obj.method(); // this는 obj를 가리킵니다.