简体   繁体   English

JavaScript回调函数的区别

[英]Javascript callback functions differences

I would like to know the difference between 2 implementations of callback functions. 我想知道回调函数的两种实现之间的区别。

This: 这个:

$("#button").on('click', function () {
            //do something
});

Versus having the function already defined. 与已经定义的功能。

$("#button").on('click', btnFunction);
function btnFunction() {
    //do something
}

Are there any implications with one compared to another? 与另一个相比,有什么影响吗? Performance-wise is one faster? 性能方面是更快吗?

The first uses an anonymous function and the second does not. 第一个使用匿名函数,第二个不使用匿名函数。 There's no difference in both. 两者没有区别。

See: Why do you need to invoke an anonymous function on the same line? 请参阅: 为什么需要在同一行上调用匿名函数?

Some folks prefer the second form because it gives a function name when using the debugger and tracing, but there are ways to get the same functionality in the first form. 有些人喜欢第二种形式,因为它在使用调试器和跟踪时会给出函数名称,但是有许多方法可以在第一种形式中获得相同的功能。

If you are attaching and removing the event handler based on changing conditions, the second form is much easier to maintain, however. 如果要根据不断变化的条件附加和删除事件处理程序,则第二种形式易于维护。

There's no difference at all, and there's no performance issue with neither one of them. 两者之间没有任何区别,而且两者都不存在性能问题。 The only difference is that in one of them you're defining the callback function as an anonymous function, this way you cannot reuse it. 唯一的区别是在其中一个中,您将回调函数定义为匿名函数,这样您就无法重用它。

The other way, where you define it else where and named it and then pass it as a callback, you're defining a function that you can later reuse in another part of your code. 另一种方法是,在其他位置定义它并命名,然后将其作为回调传递,您正在定义一个函数,以后可以在代码的另一部分中重用。

For example: if you want to do something when the document is ready, and then do se exact same thing when some one press a button you can use something like this: 例如:如果您想在文档准备就绪时执行某项操作,然后在有人按下按钮时执行完全相同的操作,则可以使用以下方法:

function getData() {
    //do something
}

$(function() {
    // Call the function once the DOM is ready
    getData();
});

// Call the same function when the button is clicked
$("#refresh_button").on('click', getData);

In most cases the first one will be used, called Anonymous Functions 在大多数情况下,将使用第一个,称为匿名函数

The second one will be used when the function is not only used inlined here, but also needs to be reused somewhere else. 当该函数不仅在此内联使用,而且还需要在其他地方重用时,将使用第二个函数。

But anyway it could be a personal preference. 但是无论如何,这可能是个人喜好。

您可以看到的唯一真正的区别是,使用第二个堆栈跟踪时(例如,如果引发了异常)堆栈跟踪会更好,即更易于调试。

Just reuse-ability. 只是重用能力。

In the second case, you could call btnFunction() somewhere else if need be. 在第二种情况下,如果需要,可以在其他地方调用btnFunction()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM