[3줄정리] High-order Function & Call-back Function
2020. 5. 4. 21:16ㆍ컴퓨터언어/Vanilla JS
728x90
반응형
// 유저로부터 키보드로 입력되는 키가 무엇인지 콘솔로 출력하는 예제
document.addEventListener("keydown", printKey);
function printKey(event) {
console.log(event.key);
}
High order function(고차함수) : 다른 함수를 인풋으로 받아들이는 함수. ex) addEventListener()
Call back function : High order function에서 인풋으로 쓰이는 함수. ex) printKey()
* 이 call back function이 먼저 실행되고 나서 실행 또는 반환되는 값을, high order function이 2차적으로 이용한다.
즉 call back function은 유저가 직접 실행시키는 것이 아니라, high order function이 간직하고 있다가 자기가 필요할 때(위 예제에서는 키가 눌렸을 때) 꺼내쓰는 것이다.
function addEventListener(typeOfAction, callbackFunction) {
// Detecting for user actions
// When detected action then:
// ...
let keyPressAction = {
actionType: "keydown",
key: "k",
keyPressDuration: 1,
}
if (keyPressAction.actionType === typeOfAction) {
callbackFunction(keyPressAction)
}
}
addEventListener는 이런 식으로 등록되어 있을 것이다.
document.anotherAddEventListener("keydown", function(event) {
console.log(event)
})
programmer는 등록되어 있는 addEventListener를 이렇게 활용할 것이다.
중요한 것은,
콜백함수는 자신을 사용해주는 상위의 함수(고차함수) 안에 들어간다는 것과,
고차함수는 자기가 가지고 있는 property나 method들을 자신에게 들어온 콜백함수로 넘겨준다는 것이다.
728x90
반응형
'컴퓨터언어 > Vanilla JS' 카테고리의 다른 글
[for loop] for 반복문의 다양한 방법 (ES6) (0) | 2020.05.19 |
---|---|
[JS] const로 선언해도 array와 object는 수정이 가능한가? (0) | 2020.05.11 |
[Javascript] JSON 핵심 정리 (0) | 2020.05.07 |
Vanilla JS 실시간 시간 뜨게 하기 (20줄도 안됨) (0) | 2020.03.31 |
Vanilla JS 마스터하기 1일차 (0) | 2020.03.31 |