this and contextthis 키워드는 어떤 코드(예를들면 함수의 body)가 실행되는 배경, 즉 context를 가리킨다.this는 보통 함수 내부에서 사용되는데, this의 값은 해당 함수가 어떻게 정의define 되었느냐가 아니라, 어떻게 호출invoke 되었느냐에 따라 결정된다.
obj.method()), this는 해당 객체를 가리킨다. (같은 메소드여도 다른 객체를 통해 호출하면 this는 바뀐다)func()), this는 전역 객체(global object)를 가리키거나(in non-strict mode), undefined 값을 가진다(in strict mode).Function.prototype.bind(), apply(), call())를 사용하면 강제로 원하는 대상에 this 를 바인딩할 수 있다.
apply, call의 경우에는 해당 메소드를 사용하여 호출할때만 일시적으로 this를 다른 대상에 강제로 바인드하여 호출할 수 있는 메소드이고,bind의 경우에는 아예 내가 원하는 대상에 this를 묶어놓은 새로운 함수를 생성하는 메소드이다. 따라서 bind로 생성한 함수는 이후 다른 객체의 메소드로 호출한다 하더라도 this가 바뀌지 않는다.this를 다르게 처리한다. 얘네는 함수가 정의되는 시점에 부모 스코프의 this를 상속받는다(they inherit this from the parent scope at the time they are defined)
this 바인딩을 가지는 것이 아니기 때문에,
bind(), apply(), call()),this가 object를 가리키지 않는다. (그래서 사실 메소드로 사용할 수 없다고 한다 Arrow function expressions 참고.)this is always a reference to an object. In strict mode, it can be any value. For more information on how the value is determined, see the description below.this context를 의미한다. 즉 this와 context는 굉장히 깊은 관계가 있다.this 문서를 보면, JavaScript에서 this 키워드는 어떤 코드가 실행되는 배경, 즉 context를 가리킨다고 설명되어 있다.
function printThis() {
console.log(this.a);
}
const obj1 = { a: 1 }
const obj2 = { a: 2 }
obj1.printThis = printThis;
obj2.printThis = printThis;
console.log(obj1.printThis === obj2.printThis) // true
obj1.printThis(); // 1
obj2.printThis(); // 2
위 코드에서 printThis 함수는 두 객체인 obj1과 obj2에 의해 실행된다.
obj1의 경우 a프로퍼티의 값으로 1을 가지고 있는 context이고, obj2의 경우 2를 가지고 있는 context이다.context 관점에서, this가 무엇을 가리킬지는 세가지 상황으로 나눠 볼 수 있다:
…그럼 각 상황에 대해 자세히 알아보자
this의 값은 함수가 어떻게 호출되었느냐에 달려 있다.undefined