简体   繁体   中英

passing parameters to anonymous functions Javascript

I could not understand why you do not need to pass the parameter name to the anonymous function inside the addEventListener . Why do you need to pass e , but not name . I mean line 6 at the end of the line, function(e)

let btn = document.querySelector(".test-btn");
  function firstFunction(e,name){
    e.preventDefault();
    btn.innerHTML = name;
  }
  btn.addEventListener("click",function(e){
    firstFunction(e, "Elon");
  });

Function parameters allow a block at some position, let's say block A, to send information to a function block at some other position, let's say Block B. When you pass a parameter, information can flow from A to B if A sends an argument and B accepts an argument.

Here, part of the information being sent is initialized inside the click callback:

btn.addEventListener("click",function(e){
  firstFunction(e, "Elon");
});

The e , the click event, is initialized by the browser and sent to the callback. But then the "Elon" string is created inside the callback. Finally, the callback does firstFunction(e, "Elon") to pass both pieces of information to the firstFunction , or the B block.

Because the extra information being passed along is created inside the click callback, and not by the caller of the click callback, the click callback only accepts one parameter, the event.

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