zbrady
zbrady

Reputation: 41

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?

Upvotes: 2

Views: 62

Answers (6)

Victor Martins
Victor Martins

Reputation: 769

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?

Upvotes: 2

Faust
Faust

Reputation: 15404

Just reuse-ability.

In the second case, you could call btnFunction() somewhere else if need be.

Upvotes: 0

Ilya I
Ilya I

Reputation: 1282

The only real difference you could see is that stack trace (if an exception is thrown for example) will be better, i.e. easier to debug, when using the second one.

Upvotes: 0

gpopoteur
gpopoteur

Reputation: 1519

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);

Upvotes: 2

NSF
NSF

Reputation: 2549

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.

Upvotes: 0

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

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.

Upvotes: 2

Related Questions