JS중급_this1

Adrian·2022년 2월 28일
post-thumbnail

▶️ this란?

console.log(this)

위 코드를 콘솔창에 쳐보면 this 키워드는 window {~~~} 와 같은 코드를 입력해준다.

function this_alert(){
	console.log(this)
}

this_alert();
  • 이 경우에도 똑같이 this라는 값은 window라고 출력된다.
  • window는 모든 전역변수, 함수, DOM을 보관하고 관리하는 전역 객체이다.

▶️ object 속의 'this'

	var obj1 ={
    	data : 'Kim',
    	mention : function(){ console.log('hi')}
    }
    
    obj1.mention();

object 자료형에는 함수를 넣을 수 있고, 이를 메서드라고 부른다.

	var obj1 ={
    	data : 'Kim',
    	mention : function(){ console.log(this)}
    }
    
    obj1.mention();

메서드 안에서 this를 입력해보면 콘솔창에 {data : 'Kim', mention : f ~~} 같은 값이 출력되는데, 이것은 obj1을 지칭하는 것이다.

  • 즉 메서드 안에서 this를 쓰면 this는 메소드를 가진 오브젝트를 의미한다.
	var obj2 ={
    	data : {
    	mention : function(){ console.log(this) }
    }
    }
    
    obj2.data.mention();

이런 원리로 위의 경우는 this는 obj2.data 임을 유추할 수 있다.

즉 this의 의미는 1.일반함수에서 쓰면 window, 2. 오브젝트 내의 함수(메서드)에서 쓰면 함수를 동작시키는 오브젝트를 의미한다.


profile
관조, 사유, 끈기

0개의 댓글