이번 주가 자바스크립트 개념 마지막이길 바라며!
this는 자바스크립트 키워드 중 하나로 자기 참조 변수
this는 사용되는 상황에 따라 다른 객체를 가르킨다 같은 함수의 형태라도 용도에 따라 다른 객체를 가르키니 유의해야 함
전역에서의 this는 전역 객체를 가르킴
console.log(this) // window
console.log(this === window)

function 키워드로 생성되며, 메서드가 아닌 함수에서는 전역 객체를 가르킴
function foo() {
console.log("function: ", this); // window
}
foo();

생성자 함수에서의 this는 생성될 인스턴스 객체를 가르킴
new 키워드가 없다면 전역 객체를 가르킴
function Food(name, color) {
this.name = name;
this.color = color;
console.log("constructor: ", this);
}
const food1 = new Food("strawberry", "red"); // food1 가르킴
const food2 = Food("banana", "yellow"); // window 가르킴

객체의 메서드에서 호출된 this는 객체를 가르킴
const obj = {
name: "soo",
age: 20,
getName: function () {
console.log("method: ", this); // obj를 가르킴
return this.name
},
};
obj.getName();

화살표 함수로 생성된 this는 호출된 환경의 this를 따라감
const arrowFunction =()=> {
console.log("arrow function: ",this) // window
}

const obj = {
name: "soo",
age: 20,
getName: function () {
console.log("method: ", this);
const getAge = () => {
console.log("arrow method: ", this);
};
getAge();
return this.name
},
};
obj.getName();

this가 가르키는 값은 개발자가 의도적으로 할당이 가능하다
함수에 this를 할당하며 함수를 실행함
function.call(this에 할당할 값, 함수 인수1, 함수 인수2, ...)
call과 같지만 인수를 배열로 전달
function.apply(this에 할당할 값, [함수 인수1, 함수 인수2, ...])
call, bind와 다르게 함수를 반환함
const returnFunction = function.bind(this에 할당할 값)
returnFunction(함수 인수1, ...)