How can I get js native onclick if I use the arrow function this to point to it?

problem description

We usually use the arrow function to get the original this, but vice versa, if the js native dom operation, such as how to get its this if onclick uses the arrow function.

the environmental background of the problems and what methods you have tried

Native operation dom

related codes

/ / Please paste the code text below (do not replace the code with pictures)

the correct way not to use the arrow function

for (let i = 0; i < iconPlus.length; iPP) {
    iconPlus[i].onclick = function () {
    //this
      clickInitModal(this);
      
    }
  }

the result I"m looking forward to.

how to get its click event this with the arrow function

Jul.11,2021

The

arrow function is not a panacea.

because you use the arrow function to trigger a function, when the callback occurs, the browser calls the function with the context of icon Plus [I], where the this points to window.

The solution to

is to go back to traditional function expressions, which is not bad. It is not necessary to abandon the old one when the new model comes out.

The

arrow function itself does not have this and arguments, and the reference to this in the arrow function is actually calling the this of the upper scope at the time of definition.
the emphasis here is on the upper scope because objects cannot form independent scopes. There is also that brothers like to use ES6 grammar so much, but some ES6 grammars can not be parsed by browsers now. There is nothing wrong with you like to use native writing. After all, it is optimized. Brother, you can continue to optimize this. You can try WEBwork. My article also explains WEBwork


The

arrow function does not have its own scope, and all this points to window.

for (let i = 0; i < iconPlus.length; iPP) {
    iconPlus[i].onclick = (event) => console.log(event);
}

try it this way. I don't know if I can get it.

Menu