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; }
Solution 1:
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 = functionsomeName() {
debugger;
}
See Named function expressions demystified for more details.
Solution 2:
Instead of saying:
var myFunction = function() {
debugger;
}
you need to say:
functionmyFunction() {
debugger;
}
This will declare the function on the first pass so that it can be referenced during program execution.
Post a Comment for "Naming A Formerly Anonymous Function Breaks"