1

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.

Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
  • 2
    Oh, it's because I have to define the function before I reference it. It has to be above in the source code order. – Phillip Senn Apr 01 '13 at 19:03
  • But isn't there a way to hoist the function declaration? – Phillip Senn Apr 01 '13 at 19:15
  • 1
    Function *declarations* are always hoisted. But what you have there is not a declaration, it's a function *expression*. See the article linked from the bottom of my answer for details. – bfavaretto Apr 01 '13 at 19:16
  • The page says that Function Declarations can not appear in Block ({ ... }). I think what this is telling me is that I shouldn't use Function Declarations inside of another function, and thereby it would place all functions in the window scope, which of course would be bad. – Phillip Senn Apr 01 '13 at 19:36
  • No, nested function declarations are fine (and desirable). That quote refers to blocks like those of `if` and `for` statements; I guess `FunctionBody` is like a special kind of block, and declarations are allowed there. – bfavaretto Apr 01 '13 at 19:39
  • I think the answer might be to use function myFunction() {} instead of var myFunction = function() {} – Phillip Senn Apr 01 '13 at 20:01
  • Philip, both methods are useful, just take hoisting differences into account when choosing one. – bfavaretto Apr 01 '13 at 20:02

2 Answers2

4

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.

Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

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.

Phillip Senn
  • 46,771
  • 90
  • 257
  • 373