728x90
this가 바인딩 되는 객체를 변경하고 싶을 때 call(),apply(),bind()를 사용한다.
1) call()
call 메소드는 모든 함수에 사용가능, this를 특정 값으로 지정할 때 쓴다
const green = {
name: "green",
age: 30
}
const blue = {
name: "blue",
age: 30
}
function showName(){
console.log(this.name);
}
showName(); //this는window
//call 메소드는 모든 함수에 사용가능, this를 특정 값으로 지정할 때 쓴다
showName.call(green); //this는 green객체
showName.call(blue); //this는 blue객체
const bella = {
name:"bella"
}
function update(birth,job){
this.birth = birth;
this.job = job;
}
update.call(green,1998,"teacher");
console.log(green);
콘솔에 {name:"green", birth:1998, job:"teacher"} 이 출력된다.
2) apply()
apply는 함수 매개변수를 처리하는 방법 외엔 call과 아예 똑같다
call은 일반적인 함수처럼 매개변수를 직접 받지만, apply는 매개변수를 배열로 받는다.
update.apply(blue,[2002,"student"]);
console.log(blue);
콘솔에 call과 동일하게 출력된다.
3) bind()
함수의 this 값을 영구적으로 바꾸고, 새로운 바인딩한 함수를 만든다
bind를 사용하는 목적은 bind 메서드는 함수에 this를 미리 적용하는 것과
부분 적용 함수를 구현하는 것이다.
mySite = {
name: 'website',
getSite:function(){
return this.name;
}
}
mySite.getSite(); //출력--> "website"
변수를 만든 후 mySite.getSite 메소드를 선언 후 실행하면 아래와 같이 undefined가 출력된다
함수의 this에 name이란 프로퍼티가 존재하지 않아 window 객체를 참조하여 값을 반환하기 때문이다
const getYoursite = mySite.getSite;
console.log(getYoursite()); //출력 --> undefined
bind() 메소드를 사용하여 this가 mySite를 가리키도록 사용해서 아래와 같이 website를 출력할 수 있다
bind()를 사용하면 this가 어떤 인스턴스를 가리킬 것인지 선택할 수 있다
const getMysite = getYoursite.bind(mySite);
console.log(getMysite()); //출력 --> "website"
bind가 call,apply와의 차이점?
함수를 실행하지 않고 함수를 생성한 후 반환하는 점이 차이점이다
728x90
'JavaScript > TypeScript' 카테고리의 다른 글
[TypeScript] 콜백 함수(callback function) (0) | 2023.02.23 |
---|---|
[TypeScript] 변수 선언문( 타입 주석, 타입 추론, any ) (1) | 2023.02.22 |
[TypeScript] 타입스크립트로 카운터 만들기 예제 (0) | 2023.02.20 |
[TypeScript] 제네릭(Generic)이란? (0) | 2023.02.17 |
TypeScript란? (0) | 2023.02.15 |
댓글