콜백 함수란?
- 정의: 함수에 파라미터로 들어가는 함수
- 용도: 순차적으로 실행하고 싶을 때 씁니다.
addEventListener
document.querySelector('.button').addEventListener('click', function () {
});
addEventListener
함수 argument 자리에 function(){}
라는 또 하나의 함수가 있습니다. 이것을 콜백함수라고 합니다.
setTimeout
setTimeout(() => {
}, 1000);
원리
function first(파라미터){
파라미터();
}
function second(){
}
first(second);
예시 1
- Q. first() 함수 다음에 second() 함수 실행하고 싶으면?
function first(파라미터){
console.log(1);
파라미터();
}
function second(){
console.log(2);
}
first(second);
콜백 함수 쓸 때 - 협업
- first함수를 만들었는데 팀원들이 자주 쓴다.
- 팀원1: first()후에 console.log(2)를 실행하고 싶은데요.
- 팀원2: first()후에 console.log(4)를 실행하고 싶은데요.
function first(파라미터){
console.log(1);
파라미터();
}
function team1(){
console.log(2);
}
function team2(){
console.log(4);
}
first(team1);
first(team2);
https://www.youtube.com/watch?v=-iZlNnTGotk