this

  • this는 기본적으로 window

  • 객체 메서드 안에서 this는 객체를 가르킴

    • 객체 메서드 : 객체 안에 있는 함수

    • 객체의 메서드 호출할 때 내부적으로 this를 바꿔줌

    • 단, 객체의 메서드를 호출한 것이 아닌, 객체의 메서드를 변수에 저장해서 호출할 경우 객체가 아닌 window를 가르킴

      1
      2
      3
      4
      5
      6
      7
      var obj = {
          a : function() {console.log(this)}
      };
      obj.a(); // obj
       
      var a2 = obj.a; 
      a2(); // window
      cs
  • 생성자 함수로 만든 객체에서 this는 인스턴스 자신을 나타냄

  • 이벤트 리스너

    • this : 이벤트 발생한 객체
    • 바뀐것이기 때문에 외울수밖에 없음
    1
    2
    3
    document.body.onclick = function(){
    console.log(this); // <body>
    }
    cs
  • 제이쿼리

    • 내부적으로 this를 클릭한 객체로 바꿔줌
    1
    2
    3
    $(‘div’).on(‘click’,function(){
        console.log(this);
    })
    cs
    • click 이벤트 안에서 메소드 나타날경우, this는 window가르킴

      • 함수의 this는 기본적으로 window라는 원칙을 따름
      • 이때 이벤트 호출한 객체를 저장하기 위해 var that = this와 같이 새로운 변수에 저장해서 사용하는 방법이 있음
    1
    2
    3
    4
    5
    6
    7
    $(‘div’).on(‘click’,function(){
        console.log(this); // div
    function inner() {
        console.log(‘inner’,this); // inner window
    }
    });
     
    cs

+ Recent posts