This article describes a small case of closures in JS learning notes. Share it for your reference, as follows:
Directly upload the code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <style type="text/css"> *{ list-style:none; } ul{ display:flex; flex-wrap:wrap; } li{ width: 20%; text-align: center; } img{ width: 90%; padding:5%; border:1px solid #ccc; border-radius:5px; } </style> <body> <ul> <li><img src="/pizza/dist/" alt=""><p><button>praise(1)</button></p></li> <li><img src="/pizza/dist/" alt=""><p><button>praise(1)</button></p></li> <li><img src="/pizza/dist/" alt=""><p><button>praise(1)</button></p></li> <li><img src="/pizza/dist/" alt=""><p><button>praise(1)</button></p></li> </ul> </body> <script type="text/javascript"> function my$(tagName){ return (tagName); } var btnObjs=my$("button"); function bb(){ var value=2; return function(){ var target= (this) ="praise("+(value++)+")"; } } for(var i=0;i<;i++){ btnObjs[i].onclick=bb() } </script> </html>
After the function is returned, the value in it is not released, so it is accumulated.
After closure, the scope chain will be extended
The role of closures, cache data, is both a disadvantage and an advantage.
Interested friends can use itOnline HTML/CSS/JavaScript code running tool:http://tools./code/HtmlJsRunTest the above code running effect.
For more information about JavaScript, readers who are interested in reading this site's special topic:JavaScript object-oriented tutorial》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage》
I hope this article will be helpful to everyone's JavaScript programming.