js

2022-06-10 what is "this"

개발하는 가오나시 2022. 6. 10. 01:05

Javascript에는 this가 있다. 이 this라는 것은 사용하는 방식에 따라 뜻하는게 달라 진다.

 

1. 일반 함수의 this / 

 일반 함수안의 this는 전역객체를 바라본다. 

2. 메소드의 this

 메소드안의 this는 메소드를 호출한 객체를 바라본다. 단 메소드를 선언할 때, 일반 함수일 경우에만 호출 객체를 바라보지, 화살표 함수의 경우 상위 스코프의 this를 바라본다.

3. 생성자함수의 this

 생성자 함수안의 this는 생성될 인스턴스 객체를 바라본다.

4, this 바인딩 함수

 Function.prototype.apply/call/bind 메소드의 첫 번째 인수로 전달한 객체를 바라본다.

 

엄격 모드에서의 this는 undefined를 값으로 갖는다.

 

1. 일반 함수의 this

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

// this === window

2. 메소드의 this

const obj = {
	nomalFunq:function(){
    	console.log(this) // === obj
    },
    arrowFunq: ()=>{
    	console.log(this) // === window
    }
}

3. 생성자 함수의 this

const ConstructorFunq = function(name){
	this.name = name;
    this.consoleThis = function(){
    	console.log(this) // 인스턴스 객체
    }
}

const instanseObj = new ConstructorFunq("gagonasi");

instanseObj.consoleThis() // instanseObj

4. this 바인딩 함수들

func.apply(thisArg, [argsArray]) 
// apply 메소드는 함수로 this바인딩한 함수에 인자를 배열로 전달하여 호출함

func.call(thisArg, a,b,c ); 
// call 메소드는 하나씩 전달

func.bind(thisArg);
// bind 메소드는 위 함수들과 달리 바인딩 까지만 해주고 호출하지 않음, 명시적 호출 () 이 필요