了解回调函数的用途 [英] Understanding callback function purpose

查看:38
本文介绍了了解回调函数的用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这更是一个普遍的问题,但是我在这里已经阅读了类似的答案,但是找不到更多的概述.我是回调的新手,我试图了解何时应使用它们.

I realise this is more of a general question, but I've read through similar answers on here but I can't find more of an overview. I'm new to callbacks and I'm trying to understand when they should be used.

MDN Web文档具有此示例;

The MDN web docs has this example;

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);

但是,我在努力将其比以下方法更有益,因为我没有将greeting函数作为参数传递?

However I'm struggling to see how this is more beneficial than the following, where I'm not passing the greeting function as a parameter?

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput() {
  var name = prompt('Please enter your name.');
  greeting(name);
}

processUserInput();

推荐答案

简单来说,您可以说回调是一种提前询问问题(或请求任务)的方式,即完成此操作时这(通常是结果).重点是搁置稍后要执行的功能,通常是因为您现在没有所需的输入来执行这些功能.您的实现与MDN的两个主要区别是,您的维护较难维护,因此很难进行测试.

In simple terms you can say a callback is a way of asking a question (or requesting a task) in advance, i.e. when you're done with this do this (usually with the result). The whole point is to set aside functions that are to be done later, usually because you don't have the required inputs to do them now. The 2 main differences between your implementation and the MDN one is that yours is harder to maintain and harder to reason about hence test.

1.维护/可重用性

假设您将几千行代码放入一个代码库中,那么您需要更改processUserInput()的功能.与更改函数processUserInput()相比,更改或编写新的回调函数要容易得多.如果processUserInput稍微复杂一点,这将是显而易见的.这也意味着与您的实现不同,MDN在各种情况下都更加有用.您只需编写不同的回调以插入processUserInput()即可在不同的情况下重复使用它,例如说再见,大写姓名等.

Imagine you're a few thousand lines of code into a code base then you're required to change what processUserInput() does. Its much easier to change or write a new callback function instead of changing the function processUserInput(). This would be evident if processUserInput was a bit more complicated. This also means the MDN one is much more useful in various scenarios unlike your implementation. You can reuse it in different situations like saying good bye, capitalizing names etc simply by writing different callbacks to plug into processUserInput().

2.测试/更容易推理

MDN实施更容​​易理解.假设函数processUserInput(greeting)可能会返回一个问候,而不是假设processUserInput()会更容易.这使测试更加容易,因为您始终可以确保MDN实现始终在给定输入的情况下返回相同的输出.

The MDN implementation is much more easier to understand. Its easier to assume that the function processUserInput(greeting) will probably return a greeting than it is to assume what processUserInput() does. This makes it easier to test because you can always be sure the MDN implementation will always return the same output given an input.

这篇关于了解回调函数的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆