학습 log (이론)/javascript
'콜백 함수' 맛보기
abbear25
2016. 10. 21. 00:49
위에서 설명했듯이 자바스크립트의 변수에는 함수도 할당 가능
함수를 호출했을 때 또다른 함수를 파라미터로 전달하는 방법
콜백함수(Callback function), 파라미터로 전달되는 함수
함수가 실행되는 중간에 호출되어 상태 정보를 전달하거나 결과 값을 처리할 때
비동기 프로그래밍(Non-Blocking Programming) 방식으로 코드를 만들 때 사용
function add(x, y, callback){
var result = x + y;\
callback(result);
}
add(1, 1,
function(result){
console.log('callback result = %d', result);
}
);
//결과: callback result = 2
함수 안에서 값을 반환할 때 새로운 함수를 만들어 반환하는 방법
function add(x, y, callback){
var result = x + y;
callback(result);
var history = function(){
return a + '+' + b + '=' + result;
};
return history;
}
var add_history = add(1, 1,
function(result){
console.log('callback result = %d', result);
}
);
console.log('other callback result = %d', add_history());
//결과: callback result = 2
//결과: other callback result = 1 + 1 = 2
맛보기가 익숙한 이유는? http://illua.tistory.com/30
반응형