Phillip Senn
Phillip Senn

Reputation: 47663

Naming a formerly anonymous function breaks

Why does this not work:

$(document).on('click','a',myFunction);
var myFunction = function() {
   debugger;
}

When this does:

$(document).on('click','a',function() {
   debugger;
}

I've started to learn more by naming all my anonymous functions and breaking them out into their own separate named functions.

Upvotes: 1

Views: 76

Answers (2)

Phillip Senn
Phillip Senn

Reputation: 47663

Instead of saying:

var myFunction = function() {
   debugger;
}

you need to say:

function myFunction() {
   debugger;
}

This will declare the function on the first pass so that it can be referenced during program execution.

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71939

You have to swap the lines:

var myFunction = function() {
   debugger;
}
$(document).on('click','a', myFunction);

Otherwise, you would be assigning undefined as the event handler, as the variable myFunction doesn't have a value yet when you were passing it to .on.

Also: assigning a function to a variable like that doesn't make it named, it's still an anonymous function, just stored in a variable. A named function would be:

var myFunction = function someName() {
    debugger;
}

See Named function expressions demystified for more details.

Upvotes: 4

Related Questions