0

I see named functions exampled this way:

var clearClick = function() {
    // do something
}

...and then used for binding like so:

$("#clear").bind(click, clearClick);

...or with the "shorthand" methodology thus:

$("#clear").click(clearClick);

But why not use a more "normal" (similar to other programming languages) construct like this:

function clearClick() {
    // do something
}

It works the same, doesn't it? Is there any disadvantage to defining functions in this traditional way? Is the previous way just jQuerians flaunting their newfangledness?

Joe
  • 15,205
  • 8
  • 49
  • 56
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

2 Answers2

3

This works Function expression

var clearClick = function() {
    // do something
}

$("#clear").bind(click, clearClick);

This does not work Function expression. The order matters here.

$("#clear").bind(click, clearClick);

var clearClick = function() {
    // do something
}

But when you declare your function using a function declaration the order does not matter. One more advantage of the below syntax is that the function name appears in debugger.

function clearClick() {
    // do something
}
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • some older browsers have bugs related to function declarations. – Brandon Aug 01 '13 at 20:46
  • 1
    This doesn't properly explain why. Please see [JavaScript Hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Scope_Cheatsheet#Hoisting) – Mulan Aug 01 '13 at 20:51
1

One reason you might want to do it is how this works:

var clearClick;
$("#clear").click(clearClick);

clearClick = function() {
    // do something
}

... lots of stuff in here ...

clearClick = function() {
    // do something different
}
Lee Meador
  • 12,829
  • 2
  • 36
  • 42