this의 기묘한 모험

sangwoo noh·2021년 7월 5일
0

JavaScript

목록 보기
5/16
post-thumbnail

1. 전역과 함수안에서 this

<script>
  console.log(this);   // window
  function checkThis() {
  	console.log(this);   // window
  }
</script>
  • window?
    모든 전역변수, 함수, DOM을 보관하고 관리하는 전역객체 입니다.
    js관련된 저장해야하는 모든 것 들이 저장된 오브젝트
    암튼 저장됨

2. use strict mode - function안에서 this

<script>
  'use strict';

  function checkThis(){
    console.log(this)
  }
  checkThis();   // undefined
</script>
  • use strict 모드의 함수에서 this 기본값은 undefined

3. method안에서 this--------#1

  • method?
    오브젝트 안에 값으로 저장된 함수입니다.
<script>
  var someObject = {
    age : 31,
    checkThis : function(){ 
                  console.log(this);
                } 
  }

  someObject.checkThis() // { age : 31, checkThis : f };
</script>

이때 this는 자신을 호출한 바로 상위의 오브젝트를 가리킨다.(최상단의 오브젝트가 아님)

4. method안에서 this--------#2

<script>
  var someObject = {
      age: 31,
      data : {
        name : "NOHSANGWOO",
        checkThis : function(){ 
                    console.log(this); 
                    },
             },
     }
  someObject.data.checkThis();  // {name: "NOHSANGWOO", checkThis: ƒ}
</script>

이때 this는 바로 상위의 오브젝트가 someObject.data를 가리키니 해당 값만 출력한다.

5. window에 직접 함수를 추가한다면?

<script>
//  (1)
  function someFunc(){
    console.log(this)
  }

//  (2)
  window.someFunc = function(){ console.log(this) };
</script>

1번과 2번의 함수 추가방식은 정확하게 동일한 의미이다.

6. constructor과 this

<script>
  function someObj() {
    this.firstName = 'NOH';
  }

  const obj1 = new someObj();
  const obj2 = new someObj();
  console.log(obj1); // {firstName: "NOH"}
  console.log(obj2); // {firstName: "NOH"}
</script>

7. eventlistener와 this

<script>
  document.querySelector('#someButton').addEventListener('click', function(e){
    console.log(this); // e.currentTarget과 같은 값
  });
</script>

8. eventlistener안 callback 함수에서 this

<script>
  document.querySelector('someButton').addEventListener('click', function(e){
    var arr = [1,2,3];
    arr.forEach(function(){
      console.log(this);  // window
    });
  });
</script>

9. object안 callback 함수에서 this

<script>
  var someObj = {
    firstNames : ['NOH', 'KIM'],
    checkFunc : function(){
        someObj.firstNames.forEach(function(){
          console.log(this); // window
        });
    }
  }
</script>

8번과 9번의 예처럼 this는 function을 만날때마다 의미가 바뀔수도 있음

10. arrow function으로 this의 의미를 고정

<script>
  var someObj = {
    firstNames : ['NOH', 'KIM', 'OH'],
    // 이때는 this가 함수를 만나서 이 오브젝트를 가리킴
    checkFunc : function(){
    	// this를 물려받은상태
    	// 이부분에서 arrowfunction적용
        someObj.firstNames.forEach(() => {
          console.log(this); // {firstNames: Array(3), checkFunc : f }
        });
    }
  }
</script>

11. arrow function으로 this의 의미를 고정2

<script>
    var someObj = {
    firstNames : ['NOH', 'KIM', 'OH'],
    // 근데 여기도 arrowfunction을 적용한다면? 이때는 this의 기준이 window인상태
    checkFunc : () => {
    	// 이부분에서 arrowfunction적용
        someObj.firstNames.forEach(() => {
          console.log(this); // window
        });
    }
  }
</script>

arrow function을 사용하면 function을 만나도 this의 의미가 변하지 않는다.
but 물려받은 상위의 this를 기준으로 변하지 않는다는거임

그지같은거 걍 안씀

profile
하기로 했으면 하자

0개의 댓글