SoFunction
Updated on 2025-04-07

Method of passing a function as a parameter in JS (summary)

Today, when registering events for elements, I encountered a problem using addEventListener. I seemed to have encountered this before. I felt it was necessary to summarize it, which is the problem caused by the js function as a parameter. First, look at the following code. Do you think there is any problem with the following code? Can id3 pop up after clicking on the element corresponding to id3?

Example 1

var obj3=('id3'); 
('click',curClick('id1'),true); 
function curClick(id){ 
    alert(id); 
} 

The answer is no, and it cannot achieve the effect I want, because this line of code will pop up id3 when the page is loaded. When I click on the element corresponding to id3, the page does not react.

So I changed the code to the following two situations:

Example 2

var obj3=('id3'); 
  ('click',function(e){curClick('id3');stopPropagation(e)},true); 
 
  function curClick(id){ 
    alert(id); 
  } 

Example 3

var obj1=('id1');  
('click',curClick1,true); 
function curClick1(){ 
 alert('okey'); 
} 

The execution is normal this time, why is this?

Because in the JS world curClick('id3') is to directly call curClick('id3') instead of passing it as a parameter. If you want to pass it as a parameter, if you don't need to pass the parameter, you can just pass the function name directly. If you need to pass the parameter, there are two solutions.

Method 1:With the help of anonymous functions, place the function to be passed in anonymous functions, and use the anonymous function as a parameter as example 2

eg: Pass function(){myfunction(val1,val2,......);} as a parameter.

second:Rewriting requires passing functions

function curClick1(val){ 
<span style="white-space:pre">  </span>return function(){ 
    alert(val); 
  }; 
} 

The above JS article (summary) of the parameter passing method (summary) of another function is all the content I share with you. I hope you can give you a reference and I hope you can support me more.