JavaScript에서의 this는 뭔가 다른 언어에서의 this 와는 다른 뉘앙스를 가지고 있다.
가끔씩 짚고 넘어가는데도 정리가 안되는 느낌이라서 한번 제대로 정리하고 가고자 한다.
JavaScript에서 this는 현재 실행 중인 함수 내부에서 현재 객체를 참조하기 위한 것이다.
this의 값은 정의할 때가 아니라 this가 포함된 함수를 호출하는 방법에 따라 결정된다.
일반적으로, this는 호출하는 객체를 참조하지만, 몇가지 경우에서 차이가 있다.
function func() {
console.log(this); // window
}
func();
const obj = {
name: "John",
sayName() {
console.log(this.name); // obj
function func() {
console.log(this); // window
}
func()
}
};
function Person(name) {
this.name = name;
}
const person1 = new Person("John");
console.log(person1.name); // "John"
const obj1 = {
name: "John"
};
function sayName() {
console.log(this.name);
}
sayName.call(obj1); // "John"
sayName.apply(obj1); // "John"
const boundFunc = sayName.bind(obj1);
boundFunc(); // "John"
정리하면,
그냥 일반적인 함수로서 호출되는 함수의 this는 전역 객체,
객체의 메소드로서 호출되는 함수의 this는 해당 객체,
new를 사용하여 생성자로 호출되는 함수의 this는 새로 생성되는 객체,
명시적으로 call, apply, bind를 사용하여 this를 지정할 수도 있다.
추가적으로 화살표 함수에서의 this는 화살표 함수를 무시하고 this가 쓰여진 곳의 상위 lexical scope에 따라 this가 결정된다.
(참고: 화살표 함수와 일반 함수의 차이)