Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between these two ways of calling a function

Tags:

javascript

PopupFirstNameButton.addEventListener('click', FirstNameFunction);

// This gets called
function FirstNameFunction(){
  alert("Hello");   
}

// This does not
var FirstNameFunction = function (){
    alert("Hello");   
}
like image 211
theJava Avatar asked Apr 19 '11 13:04

theJava


2 Answers

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

this is an assignment statement , so only after this is executed, FirstNameFunction gets assigned a value. So when PopupFirstNameButton.addEventListener('click', FirstNameFunction); is executing, FirstNameFunction is undefined

like image 120
wong2 Avatar answered Sep 28 '22 04:09

wong2


In the first example, you're creating a named function. The function's name is FirstNameFunction.

In the second example, you're creating an anonymous function (a function that has no name). However, you're also defining a variable named FirstNameFunction that holds a reference to the anonymous function. In this case FirstNameFunction is not the function itself, but is just a variable that references it.

The reason these differences are important when assigning the event handler as you did on the first line, is because global-scope named functions can be referenced from anywhere in the code, as long as their declaration has been parsed and interpreted before you try to use them. On the other hand, variables can only be used while they're in scope. That means after they're defined, and before they fall out of scope. Therefore, you should be able to use the second declaration method with your event handler assignment, as long as you declare the variable pointing to the anonymous function before you call the event handler and you do it in the same scope.

This works:

var FirstNameFunction = function (){
    alert("Hello");   
}    
PopupFirstNameButton.addEventListener('click', FirstNameFunction, false);

This doesn't:

PopupFirstNameButton.addEventListener('click', FirstNameFunction, false); // FirstNameFunction is undefined!!
var FirstNameFunction = function (){
    alert("Hello");   
}    

Neither does this:

function declareFunction()
{
    var FirstNameFunction = function (){
        alert("Hello");   
    }    
}  // FirstNameFunction falls out of scope here and is no longer declared

declareFunction(); // The anonymous function exists while this is running but the reference is lost when the function returns

PopupFirstNameButton.addEventListener('click', FirstNameFunction, false); // This doesn't work.
like image 30
Joshua Carmody Avatar answered Sep 28 '22 03:09

Joshua Carmody