Js callback function passes parameters

problem description

I want to pass a parameter of a global variable to the callback function. Although I know that it can be accessed directly without passing parameters, I want to try it, but something goes wrong. I can"t find the passed parameter in the callback function

related codes

var temp = {};
temp.index = 0;
document.getElementById("d").addEventListener("click", function (e, temp) {
  console.log(temp);
  move(e, temp);
}, false)
function move(e, obj) {
  obj.index = 2;
}

result

clipboard.png

question

I don"t understand why the method of passing parameters to global variables cannot be found in the callback function

.
Jan.27,2022

clipboard.png
people only accept one input parameter. Isn't it difficult for others to pass in two parameters


use closures

addEvent.addEventListener('click',log(''))
function log(msg){
    return function(e){
       console.log(msg)
       //to do
    }
}

there are two steps in passing parameters to a function. The first step is to declare the parameters when declaring the function, and the second step is to pass them when the function is called. These two steps are a complete process of passing parameters to the function

.
function a(x,y)(consoel.log(x,y));
a(1); // 1 undefined

above event binding is that you pass an anonymous function with temp parameters to the event callback. However, after the event is executed, the callback function is executed by the browser or engine, and it does not pass the parameters corresponding to temp, so you cannot receive it. All you can do is the following move function


I have summarized this problem and sorted it out in addeventlistener passing parameters

Welcome to the discussion

Menu