简体   繁体   中英

On passing argument to a callback function

I have some ambiguity in Javascript callback functions.

The first code is structured as follows:

function firstFunction()
{
 var message = "something";
 secondFunction(message);
}

function secondFunction(message)
{
   var myButton = document.getElementById("my-button");
   myButton.addEventListener('click',thirdFunction(message));
}

function thirdFunction(message)
{
 console.log("the messages is: "+message);
}

When I run the script above, the thirdFunction gets executed without clicking the button.

After some research, I read about the closure in Javascript. Then I changed the code to the following structure:

function firstFunction()
{
 var message = "something";
 secondFunction(message);
}

function secondFunction(message)
{
   var myButton = document.getElementById("my-button");
   myButton.addEventListener('click',thirdFunction);
}

function thirdFunction(message)
{
  return function(){
  console.log("the messages is: "+message);
  }
} 

I got the expected result. The thirdFunction is executed only when the button is clicked.

I am not sure if I my second code structure is correct? I am not sure if I'm getting the closure concept correctly as I never returned a function in conventional programming before. This is a new concept to me. Please, correct me if I'm wrong.

EDIT: Some of the solutions suggest writing it like this:

myButton.addEventListener('click', function() { thirdFunction(message) });

For code readability, I am trying to avoid this. I prefer to place the code for the thirdFunction outside the secondFunction .

Use an anonymous function to make the closure in the correct environment:

function secondFunction(message)
{
   var myButton = document.getElementById("my-button");
   myButton.addEventListener('click', function() {
     thirdFunction(message)
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM