JS - This

김종민·2023년 3월 11일
0

JS의 This는 기본적으로 window(globalThis)이다.

This는 아래의 규칙을 갖는다.

  1. JS의 this는 다른 언어와 다르게 그 값이 런타임(호출)에 결정된다.
  2. 일반 함수의 this는 전역객체를 지칭한다.
    단, obj.함수()인 경우에는 obj를 지칭한다.(call,bind등으로 this를 바꾸는경우에도 this가 변경된다)
const obj = {
	name:"min",
    callName(){
    	console.log(this.name)
		funtion inner(){
        	console.log(this.name)
        
        }
        inner()
   }
}

obj.callName()   // "min" , undefined
  1. 화살표 함수의 this는 상위 스코프(부모)를 지칭한다.
const obj = {
	name:"min",
    callName(){
    	console.log(this.name)
		const inner()=>{
        	console.log(this.name)
        
        }
        inner()
   }
}

obj.callName()   // "min" , "min"
  1. 객체 및 생성자의 this는 객체 및 생성자를 지칭한다.
profile
개발을 합시다 :)

0개의 댓글