THIS 와 함수.
this 의 값은 함수를 호출하는 방법에 의해 결정된다.
function hello(){ return this }
hello()
의문점/해결 : 왜 와이 또 window 이유가 뭐지?
let 과 const 배우며 var은 사용하지 않을것을 나에게 약속했다. 갑자기 뭔 소리냐. 콘솔을 열고 this 를 입력해서 hello( )를 찾아보자. 맙소사OMG 알고 있었지만 뭔가 반갑지 않은 친구 hello:f hello( ) 다.
전역코드에서 평가 실행 컨택스트에 환경까지 가기에는 너무 멀기 때문에 일단 우리가 어느정도 이해하는 것으로 이해하자
그래서 여기 this 가 window 로 나오는 이유는 window.hello( ) === hello( ) true 이기 때문이다.
window(전역객체) 의 hello(객체 메소드)는 (전역객체의)this를 리턴한다.
함수를 호출하는 방법을 여기서 볼수있다.
우리는 흔히 함수가 어떻게 호출됬는가 하면 '나로인해.함수( )' 왼쪽의 나로 인해 함수를 호출했다고 한다. window로 인해 호출됬으니 this는 window객체의 this 를 출력 하는 것 이다!!
const cat = {
name: "kitty",
meow() {
console.log(this.name + " : meows ");
},
};
cat.meow() //(output) kitty : meows
cat 객체의 meow함수의 this는 cat의 객체 주소를 바인딩 한 것이다.
this : { name: 'kitty', meow: [Function: meow] }
this.name: kitty
비슷한 개의 객체 추가 :
const dog = {
name: "poppy",
bark() {
console.log(this.name + " : barks");
},
};
dog.bark() //(output) poppy : barks
this : { name: 'poppy', bark: [Function: bark] }
this.name: poppy
너무 길면 재미 없으니 하나만 더 재미를 보고 파트1을 마무리 짓겟다
function hello() {
console.log(`${this} says hi`);
}
const cat = {
name: "kitty",
hello, //여기에 추가!!
meow() {
console.log(this.name + " : meows ");
},
};
hello() //(window.hello()) // [object Window] says hi
cat.hello() // (output) kitty says hi
dog.hello() // (output) dog.hello is not a function /dog에는 hello가 없으니!
이 마지막 3개의 다른점을 구별할수 있다면 this 는 다이나믹, 동적으로 값이 주어진다. 때문에 많은 사람들이 헷갈려 한다고 한다.
이전 이야기 : this의 window
다음 이야기 : (궁금증2) 그러면...Class의 constructor도 메소드 처럼 생겼으니 this.name 이라고 하면 Class를 보고 Class의name값을?!@!??!@ ㄷㄱㄷㄱ
이전 단계의 window에서 Class window 까지 너무 자연스럽게 진행될것 같아서 기쁘다