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 메소드는 위 함수들과 달리 바인딩 까지만 해주고 호출하지 않음, 명시적 호출 () 이 필요
'js' 카테고리의 다른 글
<input type='text'/> 의 이벤트를 잘 몰랐습니다. (0) | 2022.09.14 |
---|---|
[Next.js] 서버 사이드 코드에서 쿼리스트링을 어떻게 가져오는데! (0) | 2022.06.29 |
[React] state가 너무 자주 빠르게 바뀌면? (0) | 2022.06.25 |
[React] 생각을 놓으면 쉬운 것도 실수한다. (0) | 2022.06.25 |
2022-05-31 / js array.find 그리고 array.filter (0) | 2022.05.31 |