当不希望一个变量造成全局污染,又要常驻内存,就使用闭包

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. /* 当不希望一个变量造成全局污染,又常驻内存,就使用闭包 */
  12. function create(){
  13. let a = 100;
  14. return function(){
  15. console.log(a);
  16. }
  17. }
  18. /* */
  19. var fn = create();
  20. fn();
  21. /*
  22. fn = function(){
  23. console.log(a);
  24. }
  25. fn是全局变量,它没有调用a的内存就不会释放掉
  26. */
  27. </script>
  28. </body>
  29. </html>

1、闭包

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. /* 使用一个闭包函数,可以设置和获取内存,但是没办法直接获取内存 */
  12. function createCache(){
  13. const data = {} //闭包中的数据是隐藏,不return外部没办法直接访问
  14. return {
  15. set:function(key,val){
  16. data[key] = val
  17. },
  18. get:function(key){
  19. return data[key];
  20. }
  21. }
  22. }
  23. var obj = createCache();
  24. obj.set("name","cheng");
  25. obj.set("age",12)
  26. console.log(obj.get("age"))
  27. </script>
  28. </body>
  29. </html>

2、闭包封装函数防抖

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <button id="btn">btn</button>
  11. <script>
  12. var btn = document.getElementById("btn");
  13. btn.addEventListener("click",debounce(function(){
  14. console.log(this.id);
  15. }))
  16. function debounce(fn,delay=500){
  17. let timer = null;
  18. return function(){
  19. if(timer){
  20. clearTimeout(timer);
  21. }
  22. timer = setTimeout(()=>{
  23. fn.call(this);
  24. },delay)
  25. }
  26. }
  27. </script>
  28. </body>
  29. </html>