以下示例演示回调:
示例 1: - 使用回调
<script>
// The callback method
function meaningOfLife() {
console.log("The meaning of life is: 42");
}
// A method which accepts a callback method as an argument
function printANumber(number, callback) {
console.log("The number you provided is: " + number);
callback();
}
// Driver method
printANumber(6, meaningOfLife);
</script>
结果:
The number you provided is: 6
The meaning of life is: 42
示例 2: - 普通函数调用
<script>
// A simple function
function meaningOfLife() {
console.log("The meaning of life is: 42");
}
// Another simple function
function printANumber(number) {
console.log("The number you provided is: " + number);
meaningOfLife();
}
// Call to second function
printANumber(6);
</script>
结果:
The number you provided is: 6
The meaning of life is: 42
Now, when I can get my result simply by normal function calling, then what is the use case of Callback? Why so much fuss? Even by making a simple call to a method from inside another function I can achieve my task (Always). Why in world then huge fuss of callback is there? What special work has it done in this example?
最佳答案
Why in world then huge fuss of callback is there?
因为调用者决定接下来应该调用什么。
关于javascript - 简单例子中callback的使用值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39186502/