프론트엔드 스쿨 5기 TIL - 4월 13일 - this

크롱·2023년 4월 17일
0

JavaSrcipt

목록 보기
26/53

4월18일 자료도 참고하기!

🌈 this

  • this는 기본적으로 전역 객체(js-window, node-global)를 가리키고, 호출하는 것이 object이면 해당 객체를 가리킨다
  • 자기자신을 호출한 녀석을 this로 가리키게된다.
<script>
  function a() {
      console.log(this)
  }
  a() 

=>> window호출 왜냐면 this는 자신을 호출한 객체를 뜻하기때문에.
//console.log는 window에있는애 == window.console.log(), a()  == window.a() 이니까 점 앞에를 보면된다.

</script>

객체 안에 function

<script>
  let myObj = {
      val1: 100,
      func1: function () {
          console.log(this); 
          //this가 누구일까?  
          // 찍어보면됩니다 콘솔로그로.
      }
  }

  myObj.func1(); // myObj 호출  .앞에 myObj쥬
  
 --------------------------------------
 let myObj = {
    val1: 100,
    func1: function () {
        console.log(this);
    }
}

let test = myObj.func1;
test() //test를 호출한 애가 윈도우기때문에.. window 
// 난 걍 myObj 외에 아무것도 없으니 window로 올라가는거라고 생각해서 window라고 했음.
//함수의 이름은 변수, 변수는 포스트잇.가리키는거..
</script>

function 안에 function

<script>
function a(){
    console.log(this)
    function b(){
        console.log(this)
        function c(){
            console.log(this)
        }
        c()
    }
    b()
}
a() //console log찍고 b실행시킴.
//셋다 window가 뜬다. 호출한게 함수이고, 객체가 없으니까
</script>

정리

  1. 전역공간의 this는 window(node는 global)
  2. 메서드로 호출한 경우 this는 멤버접근연산자 앞에 객체
  3. 함수로 호출할 경우 this는 window(node는 global)
  4. 화살표 함수의 경우 this는 상위스코프
  5. 생성자 함수의 경우 this는 인스턴스
  6. 콜백함수의 경우 this가 다르게 동작 할 수 있음
profile
👩‍💻안녕하세요🌞

0개의 댓글