대부분의 경우 this의 값은 함수를 호출한 방법이 결정합니다.
실행하는 중 할당으로 설정할 수 없고 함수를 호출할 때 마다 다를 수 있습니다.
-MDN 문서-
일반적으로
this
를 호출한다면,this
는window
라는 전역 객체를 가리킴
(Node.js에서는Global
)
console.log(this === window); // true
함수 내부에서
this
의 값은 함수를 호출한 방법에 의해 좌우됩니다.
function func() {
return this;
}
func() === window; // true
const car = {
name: "KIA",
getName: function () {
console.log(this.name);
},
};
car.getName(); //KIA
const car2 = {
name: "Hyundai",
getName: car.getName,
};
car2.getName(); // Hyundai
const bindGetname = car2.getName.bind(car);
bindGetname(); // KIA
const testCar = {
name: "benz",
getName: function () {
console.log(this.name); // benz
const innerFunc = function () {
console.log(this.name); //undefined
};
// 화살표 함수에서의this는 함수가 속해있는곳의 상위 this를 계승 받는다.
const innerFunc2 = () => {
console.log(this.name); //benz
};
innerFunc();
innerFunc2();
},
};
testCar.getName();
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this
https://hanamon.kr/javascript-this%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C/
https://www.youtube.com/watch?v=tDZROpAdJ9w&t=449s