Callback
함수를 호출할 때, 인자로 함수를 전달하는 기술
☆ Code
<!doctype html>
<html>
<head>
<title>Callback</title>
</head>
<body>
</body>
<script>
function complexCal(num1, num2, callback){
if(callback){
callback(num1 * num2);
}
else{
console.log("[complexCal] " + (num1*num2));
}
}
function printHTML(data){
document.write("<h2>드디어 밀수품을 팔았다</h2>");
document.write("<h2>판 가격 : " + data + "</h2>");
}
function callToPolice(data){
document.write("<h2>경찰서에 연락할 것임</h2>");
document.write("<h3>귀하는 " + data + "원 횡령죄</h3>");
}
// printHTML(300);
complexCal(139, 203);
complexCal(139, 203, printHTML);
complexCal(139, 203, callToPolice);
// 상품명, 가격, 개수를 전달받은 후 전체 금액을 출력
// 만약 callback이 있다면 데이터를 넘겨준다.
// callback에는 영수증 출력 기능을 넣어보도록 한다.
function pay(name, price, count, callback){
let total = price * count;
console.log("상품 : " + name);
console.log("가격 : " + price);
console.log("개수 : " + count);
console.log("합계 : " + total);
if(callback){
callback(name, total);
}
}
function printAll(name, total){
with(document){
write("<h1>쇼핑영수증 도착</h1>");
write("<hr>");
write("<h2>[" + name + "] " + (total*2) + "원</h2>");
write("<hr>");
write("<h3>바가지쇼핑센터</h3>");
}
}
function printOnlyOne(name){
document.write("<h1>" + name + "</h1>");
}
pay("재활용봉투", 290, 10, printAll);
pay("재활용봉투", 290, 10, printOnlyOne);
</script>
</html>
'JavaScript' 카테고리의 다른 글
JS 배너 (0) | 2024.12.04 |
---|---|
JS dom (0) | 2024.12.03 |
JS json (0) | 2024.12.01 |
JS 객체 (0) | 2024.12.01 |
JS 지역변수와 전역변수 (0) | 2024.11.26 |