this 키워드

dongwon·2021년 5월 31일
0

1. 단독으로 this를 호출 한 경우는 global object를 가리킴 - window{...}

 console.log(this)  //Window{...}  (글로벌 오브젝트)

2. 함수 안에서 호출 한 this도 window객체에 바인딩

function myFnc() {
  console.log(this);
}
myFnc();  //Window{...}

3. strict mode일 때 함수 안에서 쓰면 this는 undefined

<script>
  'use strict';

  function myFnc(){
    console.log(this); //undefined
  }
  myFnc(); 
  
</script>

4.오브젝트 자료형 안에 있는 함수(오브젝트안의 메소드)의 this는 함수를 갖고 있는 바로 위의 오브젝트를 가리킴

console.log(this)  //Window{...}

var obj1 = {
  data : 'Kim',
  myFnc : function(){ console.log(this) } 
}
obj1.myFnc(); //콘솔창에  { data : ‘Kim’, myFnc : f } 출력됨 


//오브젝트 안에 오브젝트 안의 메소드의 this 
var obj1 = {
  data : 'Kim',
  obj2 : {
    data : 'Pack',
    myFnc : function(){ console.log(this) } 
  }
  
}
obj1.obj2.myFnc(); //콘솔창에  { data : ‘Pack’, myFnc : f } 출력됨 

4-2 아까 위의 "2. 함수 안에서 호출 한 this도 window객체에 바인딩" 이라는 내용도 결국 window라는 커다란 오브젝트 안에 있는거니까

window : {

	function myFnc() {
      console.log(this);
	}
  	myFnc(); //Window{...}
}

5.Arrow Function은 this 값을 함수 스코프 바로 밖깥에 있는 상위 함수의 this를 가져오거나, 상위 class에서 값을 물려받음

console.log(this)  //Window{...}


var obj1 = {
  data : 'Kim',
  obj2 : {
    data : 'Pack',
    myFnc : ()=>{ console.log(this) } // obj1 밖의 Window객체의 this
  }
}
obj1.obj2.myFnc();

6.이벤트핸들러, 이벤트리스너 안에서의 this는 바인딩 된 HTML DOM요소를 가리킴(this == e.currentTarget )

<button id="btn">버튼</button>
document.getElementById('btn').addEventListener('click', function(e){
  console.log(this); //콘솔창에 <button id="btn">버튼</button> 출력
  console.log(e.currentTargaet); //콘솔창에 <button id="btn">버튼</button> 출력

7.생성자 안에서의 this는 생성자 함수가 생성하는 객체로 this가 바인딩

function Person(name) {
  this.name = name;
}
var kim = new Person('kim');
 
console.log(kim.name); //kim
profile
What?

0개의 댓글