Javascript binding event handler function by name

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}

Why does this work...

$("#clickme").click( showAlert );

function showAlert() {
  alert( "Hiya" );
} 

... but not this...?

$("#clickme").click( showAlert );

var showAlert = function() {
    alert( "Hello" );
}

This is happening due to hoisting.
In your first case, the code is interpreted as (notice how the function declaration is being evaluated first):

function showAlert() {
   alert( "Hiya" );
}
$("#clickme").click( showAlert ); 

And your second is interpreted as :

var showAlert;
$("#clickme").click( showAlert );

showAlert = function() {
   alert( "Hello" );
}

Since showAlert is a variable declaration and not a function declaration (notice the var keyword), the variable declaration is evaluated first, and by the time you bind the event handler, the showAlert variable is declared, but it holds the undefined value.

This is what hoisting does : it hoists variable and function declarations to the top of the closure.
There are a couple of good resources on hositing out there, including here on SO.


The first is a Function Declaration..

The second is a function Expression..

Function Declarations are first read before any code is executed.

So the first case works . The second method does not work as that was not defined yet by the time the function is being assigned to it,..

So this will work

var showAlert = function() {
    alert( "Hello" );
}

$("#clickme").click( showAlert );

ie, defining the function and then assigning the handler

链接地址: http://www.djcxy.com/p/2842.html

上一篇: 为什么JavaScript说数字不是数字?

下一篇: Javascript绑定事件处理函数的名字