function main() {
console.log(this);
}
console.log(window);
위에서는 글로벌 윈도우를 객체로 this가 가르키고있다. 왜냐하면 호출하는 주체가 윈도우라서.
const object = {
name: "태환",
};
object.main = main;
object.main();
위에서는 오브젝트라는 객체가 main함수를 호출하고있고 this는 오브젝트객체를 가르키게된다.
즉 누가 호출을 하느냐가 관건이다.
function main() {
console.log(this);
}
const mainBind = main
위와같이 하면 똑같이 글로벌 윈도우를 this가 가르키고있게된다.
const mainBind = main.bind({ sexy: "like" });
위와 같이 동적으로 움직이는 this를 추적하기 귀찮을때 bind를 사용하여 고정시켜버릴수있다.
mainBind();
const object = {
mainBind,
};
object.mainBind();
//원래는 이렇게 했으면 this가 object를 가르키고있어야하는데 여전히 bind시킨 객체가 나온다.
//* 주의 해야 할것은 한번 bind시킨건 반복하여 bind가 불가능하다. 해봤자 뒤에건 무시된다. /
const 객체 = {
name: "this 정복하기",
main: function () {
console.log(this);
}.bind({ whatthe: "속았징? 여기를 디스가 보고있징~ 이렇게 쓸수 있징~" }),
};
객체.main();
위와 같이 함수끝에 바로 bind 시킬수있다
화살표 함수는 this가 호출에 따라 바뀌지 않는다. 동적으로 움직이는 this를 위에서는 bind
로 처리했는데 이와같이 귀찮은일이 생기지 않는다.
function test() {
console.log(this);
}
const 객체 = {
name: "태환",
test: {
name: "과연?",
testfunc: () => console.log(this), // {} ??
},
};
객체.test.testfunc();