回调 javascript_了解JavaScript回调

回调 javascript

Callbacks are frequently mentioned in the context of functions and events, but can also be one of the more difficult aspects of JavaScript to understand. So what are callbacks, and how do they work?

在函数和事件的上下文中经常提到回调,但是回调也可能是JavaScript较难理解的方面之一。 那么什么是回调,它们如何工作?

You’re probably already familiar with callbacks; for example, they frequently appear inside event listeners:

您可能已经熟悉回调。 例如,它们经常出现在事件监听器中

button.addEventListener("click", function() {
    … do something
})

See the function() reference? That’s an example of a callback.

看到function()参考吗? 那是一个回调的例子。

This callback function is also anonymous and a closures. This callback approach can also be referred to as a function expression or a wrapping function

这个回调函数也是匿名的和闭包的。 这种回调方法也可以称为函数表达式包装函数

为什么需要回调? (Why Are Callbacks Necessary?)

is event-driven: it executes in the order that events happen and results are produced, not necessarily in the order that code appears. This means that code like the following:

事件驱动的 :它按事件发生和产生结果的顺序执行,而不必按代码出现的顺序执行 。 这意味着代码如下所示:

function first() {
    …do something that takes a lot of calculation…
    console.log("First");
}
first();

Will print First in the console after the calculations are complete.

计算完成后,将在控制台中 首先打印。

I’ll change this function so that it is actually slowed before it gets to print out First, and add a second one that executes almost instantly:

我将更改此函数,以使其在打印出First之前实际上变慢,然后添加几乎立即执行的第二个函数:

function first() {
    setTimeout(function() { console.log("First"); }, 1000);
}

function second(){
    console.log("Second");
}

first();
second();

The result in the console will be produced in a different order than what we might expect:

控制台中的结果将以与预期不同的顺序生成:

Second
First

Why? During exection, JavaScript finds the first() function and starts to run that. Then, without pausing, it goes ahead and finds the second function and runs that too. JavaScript never stops, and is always looking for more work to do: that’s one of the reasons it runs so fast in modern browsers.

为什么? 在执行期间,JavaScript找到first()函数并开始运行它。 然后,在不暂停的情况下 ,它继续进行并找到第二个函数并运行它。 JavaScript永不停止,并且一直在寻找更多工作要做 :这就是它在现代浏览器中如此快速运行的原因之一。

It’s important to note that callbacks are just a convention for using functions in a certain way in JavaScript: there’s no explicit type of “callback function”. Callbacks began to be heavily featured in ES5 (the previous JavaScript standard) and JQuery; they’re now a very common web developer coding technique.

重要的是要注意,回调只是在JavaScript中以某种方式使用函数约定 :没有“回调函数”的显式类型。 回调在ES5(以前JavaScript标准)和JQuery中开始成为重要功能。 它们现在是非常常见的Web开发人员编码技术。

整理回调 (Tidying Up Callbacks)

In the case of the event listener example we started with, we wait for the click event to complete before we execute the rest of the code. But if you’re only doing one thing, it may be better that the callback is substituted with named functions:

在我们开始的事件侦听器示例中,我们执行其余代码之前等待click事件完成。 但是,如果您只做一件事,则最好用命名函数代替回调:

function makeMenu() {
    … do something …
}
button.addEventListener("click", makeMenu);

This will have the same result, but abstracts the code, and makes the makeMenu function reusable by other parts of our script. However, one potential problem of this approach is that including parameters in the function will cause it to fire immediately, without any click taking place at all:

这将具有相同的结果,但是将代码抽象化,并使makeMenu函数可被脚本的其他部分重用。 但是,此方法的一个潜在问题是,在函数中包含参数将导致其立即触发,而根本不会发生任何单击:

function makeMenu(param1) {
    console.log("Clicked");
}
button.addEventListener("click", makeMenu(param1));

The result in the console, without the button ever being clicked, will be:

在控制台中, 如果没有单击按钮 ,结果将是:

Clicked

In other words, the JavaScript is firing the event without any action taking place. To get around this, we can go back to a formal callback:

换句话说,JavaScript会触发事件,而不会执行任何操作。 为了解决这个问题,我们可以返回一个正式的回调:

function makeMenu(param1) {
    console.log("Clicked");
}
button.addEventListener("click", function() { makeMenu(param1) } );

Alternatively, you can .bind() the parameters:

或者,您可以.bind()参数:

button.addEventListener("click", function() { makeMenu.bind(null, param1) } );

It’s also possible to shorten the first example using an ES6 arrow function:

也可以使用ES6箭头功能来简化第一个示例:

button.addEventListener('click', () => makeMenu)

I’ll have more to say about arrow functions in a future article.

在以后的文章中,我将更多地讨论箭头功能。

I’ll talk more about .bind(), together with advanced features of callbacks, in the next article.

在下一篇文章中,我将详细介绍.bind()以及回调的高级功能。

You might begin to suspect that using many callbacks together to “chain” events will result in extremely complex nested JavaScript, and you’re right. Callback Hell has some good advice about dealing with this problem, and future articles on this site will deal with this common problem too.

您可能会开始怀疑,将许多回调一起用于“链接”事件会导致极其复杂的嵌套JavaScript,这是对的。 Callback Hell对于处理此问题有一些很好的建议,此站点上的后续文章也将处理此常见问题。

结论 (Conclusion)

In essence, callbacks are a way to control the order of execution in JavaScript: they’re a way to make things happen in logical order. This is also known as asynchronous JavaScript: passing a function as a parameter to say “do this in the future”. (How much in the future, or the conditions under which that future event takes place, being part of the callback and the function). In ES6, this can also be the purpose of Promises.

从本质上讲,回调是一种控制JavaScript执行顺序的方式 :它们是使事情按逻辑顺序发生的一种方式。 这也称为异步 JavaScript:将函数作为参数传递以表示“将来执行此操作”。 (作为回调和函数的一部分,将来发生多少 ,或发生将来事件的条件 )。 在ES6中,这也可能是Promises的目的。

Callbacks appear throughout JavaScript, and are part of the language itself: window.requestAnimationFrame() is an example of a callback that executes once the browser indicates it is ready to paint something to the screen, allowing for smooth animation.

回调出现在整个JavaScript中,并且是语言本身的一部分: window.requestAnimationFrame()是回调的一个示例,一旦浏览器指示它准备在屏幕上绘画某些内容,就可以执行该回调,从而实现平滑的动画。

The “run constantly” aspect of JavaScript - “listen for events all the time, and react to everything immediately” - also influences aspect of performance, especially in events that are fired frequently, such as window scrolling, resize, and use of some form inputs such as range. I’ll address that in an article on performance throttling.

JavaScript的“不断运行”方面-“始终监听事件,并立即对所有事件做出React”-也影响性能,尤其是在频繁触发的事件中,例如窗口滚动调整大小和使用某种形式输入,例如range 。 我将在有关性能限制的文章中解决这一问题。

The event-driven nature of JavaScript is also controlled to some degree by closures, scope and context, which I cover in separate articles.

JavaScript的事件驱动性质在某种程度上也受闭包, 作用域和上下文的控制,我在单独的文章中对此进行了介绍。

翻译自: https://thenewcode.com/1140/Understanding-JavaScript-Callbacks

回调 javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值