<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"contents="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Real world event listener accessing its closure</title><style>main{max-width:11ch;display:flex;flex-direction:column;align-items:stretch;}</style><script type="module">// `isClicked` is part of `clickListener`'s closure;letisClicked=false;constbuttons=document.querySelectorAll('.button');buttons[0].addEventListener('click',clickListener);buttons[1].addEventListener('click',simpleListener,{once:true});// ---functionclickListener(event){// accessing/mutating `isClicked` in the "enclosing" closureif(!isClicked){isClicked=true;event.target.textContent='Thank You!';return;}alert(`That's quite alright, thank you!`);event.preventDefault();event.stopPropagation();}functionsimpleListener({target}){target.textContent='Thank You!';target.disabled=true;}</script></head><body><main><buttonclass="button">Click Me</button><buttonclass="button">Me Too!</button></main></body></html>
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Discussion on: 😇 "Javascript Closure" I think you can get what it is finally after reading this
For further actions, you may consider blocking this person and/or reporting abuse