call, apply, bind :
함수 호출 방식과 관계없이 this를 지정할 수 있다.
call
콜 메서드는 모든 함수에서 사용할 수 있으며, this를 특정값으로 지정할 수 있다. 매개변수가 있으면 호출하며 실행한다
const mike={
name : "Mike",
};
const tom ={
name: "Tom",
};
function showThisName(){
console.log(this.name);
};
showThisName(); //""
showThisName.call(mike); //"miki"
/////////update를 만들어 내용을 더 추가하자
const mike={
name : "Mike",
};
const tom ={
name: "Tom",
};
function showThisName(){
console.log(this.name);
};
function update(birthday, occupation){
this.birthday=birthday;
this.occupation=occupation;
}
update.call(mike, 1999, "singer");
console.log(mike);
apply
apply는 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같다.
call는 일반적인 함수와 마찬가지로 매개변수를 직접 받지만,
apply는 매개변수를 배열로 받는다.
//위 코딩에서 실행 부분을 이렇게 바꾼다. call을 apply로 그리고 배열로 바꿔준다. 그러면 동일한 결과가 나온다.
update.applyl(mike, [1999, "singer"]);
console.log(mike);
///최대값과 최소값을 구할 때 유용
const minNum=Math.min(3,10,1,6,4);
const maxNum=Math.max(3,10,1,6,4);
console.log(minNum); //1
console.log(maxNum); //10
=========> 배열로 바꿔서 구하려면
const nums= [3,10,1,6,4];
const minNum=Math.min(...nums)
const maxNum=Math.max(...nums);
console.log(minNum);
console.log(maxNum);
=============>apply와 call를 적용해서 최소값 최대값 구하면
const nums= [3,10,1,6,4];
//const minNum=Math.min(...nums)
//const maxNum=Math.max(...nums);
const minNum=Math.min.apply(null,nums);
//= Math.min.aooly(null, [3,10,1,6,4])
const maxNum=Math.max.call(null,...nums);
//=Math.min.apply(null,3,10,1,6,4)
console.log(minNum);
console.log(maxNum);
bind
함수의 this 값을 영구히 바꿀 수 있다.
const mike={
name:"Mike",
};
function update(birthYear, occupation) {
this.birthYear=birthYear;
this.occupation=occupation;
}
const updateMike=update.bind(mike);
updateMike(1980, 'police');
console.log(mike);
//실제 사용 예제
const user={
name : "Mike",
showName : function (){
console.log('hello, ${this.name}');
},
};
user.showName();
let fn=user.showName;
fn(); //hello만 나온다.
fn.call(user); //hello,mike
fn.apply(user); //hello.mike
//바인드를 이용해서 새 함수로 만들기
let boundFn=fn.bind(user);
boundFn()
'JavsScript' 카테고리의 다른 글
Class (ES6에 추가된 스펙) (0) | 2022.10.02 |
---|---|
상속, prototype (0) | 2022.02.26 |
setTimeout/SetInterval (0) | 2022.02.25 |
클로저 Closure (0) | 2022.02.25 |
전개구문 Spread syntax : 배열 (0) | 2022.02.24 |