wkm
wkm

Reputation: 1762

Difference in specifying a named function for handler or anonymous function?

When specifying a handler function in jQuery, is there a difference between specifying a named function for a handler or wrapping your named function in an anonymous function?

Specifying a named function:

$( "#foo" ).on( "click", bar);

versus wrapping named function in an anonymous function:

$( "#foo" ).on( "click", function() {
  bar();
})

Upvotes: 3

Views: 93

Answers (3)

Barmar
Barmar

Reputation: 780798

They're almost equivalent. The equivalent version with the anonymous function would be:

$( "#foo" ).on( "click", function(event) {
    bar.call(this, event);
});

When jQuery runs an event handler, it binds the context to the target element. this.bar() passes that binding along to the function.

If you want to be able to remove a specific handler with .off(), you need to use the first version with the named function. If you use an anonymous function, there's no way to refer to it when removing it.

Upvotes: 1

goat
goat

Reputation: 31813

As other have said, a named function usually implies you have a reference to the function object, which allows you to easily remove the event handler without resorting to less eloquent tactics.

But, a named function in general is nicer if you use javascript debuggers. It's really nice when looking at a stack trace if each stack frame has a sensible name instead of "annonymous function".

PS - you can name the function expression like so

$( "#foo" ).on( "click", function bar() {
    // "this" will be bound to the clicked element
});

Giving you short syntax, a named function to later remove the event handler with, useful binding of "this", and better stack traces.

Upvotes: 1

John C
John C

Reputation: 666

Only if you want to be able to call the function again later.

Upvotes: 1

Related Questions