javascript - 简单例子中callback的使用值(value)

标签 javascript function callback

以下示例演示回调:

示例 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/

相关文章:

javascript - 将数据传递给回调函数的最佳方法是什么?

javascript - 无法隐藏包含特定文本的链接

function - LUA:在类中使用其名称(字符串)调用函数

c - 如何知道数组中有多少个模式段?

c - 我如何使用从 c 中的函数返回的值

javascript - canvas 上下文 - 缓存 window.requestAnimationFrame 回调函数的变量值

android - Facebook 对话教程 - 是否缺少某些内容?

javascript - 取消 Web Worker

javascript - 将 session 注入(inject)模型

javascript - Nextjs useEffect 和 useState Hook 不适用于生产