0

JavaScript中的回调

 1 year ago
source link: https://xushanxiang.com/callback-in-javascript.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript中的回调

作者: xusx 分类: JavaScript 发布时间: 2022-11-15 17:34 浏览:9

我通常使回调定义如此简单:回调是function作为 a 传递的function argument(或对象属性,如果您使用对象作为函数参数)。稍后,我们传递的那个函数将在其中执行。让我们举个例子。我为自己简化callback了定义。

如果你还是不明白,也许这个例子能让你明白。

const multiply = ({ numb1, numb2 }) => {
    return numb1 * numb2;
};

const sum = ({ numb1, numb2 }) => {
    return numb1 + numb2;
};

const doWith2Numbers = ({ cb, numb1, numb2 }) => {
    return cb({ numb1, numb2 });
}

doWith2Numbers({ cb: multiply, numb1: 2, numb2: 3 }) // 6
doWith2Numbers({ cb: sum, numb1: 2, numb2: 3 }) // 5
JavaScript

我们有两个函数可以将两个数字相乘和相加。到目前为止,您可能会想,“我们可以像这样简单地调用该函数。”

multiply({ numb1: 2, numb2: 3 })
sum({ numb1: 2, numb2: 3 })

它也是一种有效的语法,但我们没有以后可以重用的蓝图。numb2这个简单的例子:如果是 2、3 或 4,我什么也不想做。

而不是编辑我们创建的所有函数 (multiplysum)。我们可以只编辑doWith2Numbers.

const doWith2Numbers = ({ cb, numb1, numb2 }) => {
    const nothingNumbers = [2, 3, 4];
    if (nothingNumbers.includes(num2)) return undefined;
    // other code
}

另一个例子:我们是一个包的创建者,但我们真的不知道我们的包会做什么。我们只知道函数接收参数。我们将把剩下的交给其他开发人员来描述功能。在使用 Web 框架 Express.js 时,我们会经常使用回调。

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK