JS
this와 this를 지정하는 방식 call, apply, bind에 대해 알아보자
limew
2024. 4. 20. 21:14
Background
const stephen = {
age: 12
};
function printAge() {
console.log(this.age);
}
printAge(); // undefined
왜 age가 출력되지 않은걸까?
- this는 stephen이 아닌 window를 가리키고 있다.
- 함수는 별도의 this 지정을 안 해주면 window 객체를 가리킨다.
this란
- 함수를 실행한 객체를 가리키는 키워드이다
- 함수를 호출할 때 결정된다.
- 전역범위에서 this는 전역객체를 가리킨다
- 함수에서 호출되면 this는 함수를 호출한 객체를 가리킨다
- 일반함수 호출이면 : 전역객체
- 메소드 호출이면 : 메소드가 속한 객체
- 생성자 함수 호출이면 :생성된 객체
- 이벤트핸들러에서 this는 이벤트를 발생시킨 요소를 가리킨다
call(), apply(), bind()를 사용하면 this를 명시적으로 지정할 수 있다.
1. Call
함수.call(지정할 this, 매개변수)
const stephen = {
age: 12
};
function printAge() {
console.log(this.age);
}
printAge.call(stephen); // 12
call의 처음인자는 this, 그 다음부터 매개변수를 넣을수 있다
function printAge(sex, location) {
console.log(this.age, sex, location);
}
printAge.call(stephen, "man", "shanghai"); // 12 man shanghai
2. Apply
apply는 call과 유사하지만 배열형태의 매개변수를 받는다.
printAge.apply(stephen, ["man", "shanghai"]); // 12
배열을 매개변수로 넣을때 유용함
3. Bind
Call, Apply와 달리 영구적으로 this를 바인딩하는 함수를 리턴한다.
function printAge(sex, location) {
console.log(this.age, sex, location);
}
const bindedPrintAge = printAge.bind(stephen, "man", "sh");
bindedPrintAge();
concolusion
- call(this, parameter)
- apply(this, [parameter])
- const binded = func.bind()