[JS] 자바스크립트에서 상황별 this

Dev_JDra·2021년 12월 20일
0

JS

목록 보기
1/1

📖 호출에 따라 달라지는 this

1. 그냥 쓰거나 함수 안에서 쓰면 {window} 출력

  console.log(this) //{window}

  function 함수(){
    console.log(this); //undefined
  }

👉 결과

this를 출력하면 window가 나오는 이유 ..?

  • 함수나 변수는 window라는 global object 안에서 만들어지기 때문에 오브젝트 내 함수(메소드)안에서 사용하면 그 함수를 가지고 있는 오브젝트 -> window를 나타냄
    <script>
      window :{
        함수(){
          console.log(this)
        }
      } 
    </script>

2. 오브젝트 내 함수(메소드) 안에서 쓰면 그 함수를 가지고 있는 오브젝트를 뜻한다.

  var obj = {
    data : {
      func : function(){
        //함수를 가지고 있는 오브젝트
        console.log(this)//data{}
      },
      func2 : () => { 
        //Arrow Function 특징 : this값을 함수밖에 있던거 그대로 씀
        console.log(this) //window{}
      }
    },
    func : function(){
      // this = 나를 포함하고 있는 오브젝트
      console.log(this); //obj{}
    }
  }

  obj.data.func();
  obj.data.func2();
  obj.func();

👉 결과


3. Constructor안에서 쓰면 새로 생성되는 오브젝트를 뜻한다

        function machine(){ //오브젝트 생성기계(constructor)
            this.name = 'kim' //새로생성되는 오브젝트(instance)
        }

        var obj = new machine();

4. 이벤트 리스너 내부에서는 e.currentTarget

document.getElementById('button').addEventListener('click',function(e){
  //지금 이벤트 동작하는곳
  console.log(this); //button 출력
  console.log(e.currentTarget); //button 출력

  var arr = [1,2,3];
  arr.forEach(function(a){ 
    //콜백함수 => 함수 안에 들어가는 함수를 콜백함수
    //Case study) 콜백함수(일반함수)이기 때문에 window출력
    console.log(this)
  })
})

👉 결과


5. 오브젝트 내에서 콜백함수를 쓴다면 this는?

var object = {
  names : ['김', '이', ' 박'],
  func : function() {
    console.log(this); // 위 함수를 소유한 object
    object.names.forEach(function(){
      //콜백함수(일반함수)이므로 window
      console.log(this)//window
    })

    //Case Study) arrow function안에서의 this?
    object.names.forEach(() => {
      //내부의 this값을 변화시키지 않음(외부 this값 그대로 재사용)
      console.log(this)//위 함수를 소유한 object
    })
  }
}

object.func();

👉 결과

0개의 댓글