This is the 16th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

What is a closure? What is the impact on the page?

  • Closures have three characteristics
    • Function nested function
    • Functions can refer to external parameters and variables
    • Parameters and variables are not collected by the garbage collection mechanism
  • Disadvantages of closures
    • Resident memory, increase memory usage, improper use will cause memory leakage
  • Advantages of closures
    • Variables reside in memory for a long time
    • Avoid contamination of global variables
    • Creation of private members

Why use closures?

  • Design private methods and variables
  • Avoid global variable contamination
  • You want variables to stay in memory for a long time

application

  • Modular code, reduce global variable pollution
// Modularize code to reduce pollution of all variables
var abc = (function () {
  var a = 1
  return function () {
    a++
    alert(a)
  }
})()
abc() / / 2
abc() / / 3
Copy the code
  • Presence of private members (members that do not want access outside the method)
// Private member
var a = function () {
  var b = 1
  function cc() {
    console.log(b++)
  }
  function dd() {
    console.log(b++)
  }
  return {
    c:cc,
    d:dd
  }
}
var m = a()
m.c() / / 1
m.d() / / 2
Copy the code
  • Use anonymous functions for accumulation
// Use accumulation with anonymous functions
function box () {
  var num = 1
  return function () {
    num++
    console.log(num)
  }
}
var add = box()
add() / / 2
add() / / 3
Copy the code
  • Find the index of the corresponding element directly in the loop
// Find the index of the corresponding element directly in the loop
1 / / method
window.onload = function () {
  var li = document.getElementsByTagName('li')
  for (var i = 0; i < li.length; i++) {
      li[i].index = i
      li[i].onclick = function (){
        alert(this.index)
      }
  }
}
2 / / method
window.onload = function () {
  var li = document.getElementsByTagName('li')
  for (var i = 0; i < li.length; i++) {
      li[i].onclick = (function (a){
        return function () {
          alert(a)
        }
      })(i)
  }
}
Copy the code

increase

  • In fact, every single one of themjsFunctions are closures, onejsFunction of theThe top-level scope iswindowobject.jsThe execution environment itself is onescope(browser’sThe window/global node), we often call this the global scope.
  • Every function, no matter how deep, can be considered globalscopeCan be understood as a closure.

What operations cause memory leaks?

  • Memory leak: Memory that is no longer needed is not released in time
  • The garbage collector periodically scans objects and counts the number of other objects that refer to each object. If the number of references to an object is zero (no other object has ever referenced the object), or if the only reference to the object is circular, then the object’s memory is reclaimed

Operation:

  • Unexpected global variables: global variable references, undeclared variables. When global variables are used incorrectly and not recycled in time (manual assignment)null), or typos, etc. when a variable is mounted to a global variable
  • Forgotten timer or callback function:
    • DOMThe normal life cycle of an element depends on whether it is mounted inDOMTrees, when fromDOMWhen the trees are removed, they can be destroyed for recycling.
    • But if someoneDOMElements, injsWhen it also holds a reference to it, then its life cycle is defined byjsAnd whether theDOMThe treeThe decision toRemember when you remove it, both areas need to be cleaned up before it can be recycled properly
    • setTiemoutIt’s gonna have the same problem, so when you don’t have tointervalortimeoutIs best calledclearIntervalorclearTimeoutTo clear the
// clearInterval is called. If it is not cleared, it causes a memory leak. Not only that, but if the callback function is not recycled, then the dependent variables inside the callback function cannot be recycled either. So in the above example, someResource cannot be recycled.
// Get data
let someResource = getData()
setInterval(() = > {
  const node = document.getElementById('Node')
  if(node) {
    node.innerHTML = JSON.stringify(someResource))
  }
}, 1000)
Copy the code
  • Out of theDOMReferences to: use variable cachingDOMAfter the node is referenced, the node is deleted if the referenced variable is not cachedempty, still can’t do GC, and there will be a memory leak.
<div id="root">
<ul id="ul">
  <li></li>
  <li></li>
  <li id="li3"></li>
  <li></li>
</ul>
</div>
<script>
  let root = document.querySelector('#root')
  let ul = document.querySelector('#ul')
  let li3 = document.querySelector('#li3')
  
  // Because ul variables exist, the entire UL and its children cannot be GC
  root.removeChild(ul)
  
  // The ul element cannot be GC because the li3 variable references the children of ul
  ul = null
  
  // There are no variable references, so GC is available
  li3 = null
</script>
Copy the code
  • Closures: Improper use of closures can cause memory leaks, so empty objects last
/ / 1. Closure
function fn () {
  var num = new Array(10).fill('ok')
  return function () {
    console.log(num)
  }
}

let fn1 = fn()
fn1()
// After the function call, the external reference relationship is empty
// We can release the num variable of the function and the external function
fn1 = null
Copy the code

expand

  • The Necessity of garbage collection (from the Definitive JavaScript Guide (4th edition))

Because strings, objects, and arrays have no fixed sizes, they can only be allocated dynamically when their sizes are known. Every time a JavaScript program creates a string, array, or object, the interpreter must allocate memory to store that entity. Whenever memory is allocated dynamically like this, it must eventually be freed so that it can be reused, otherwise the JavaScript interpreter will consume all available memory in the system, causing the system to crash.

  • The mechanism of garbage collection is to find variables that are no longer used, and then release the memory occupied by them. However, this process is not real-time, because it is expensive, so the garbage collector will execute it periodically at fixed intervals.
  • Write an object that is not usednull

Refer to the article

  • There may be a memory leak in your program

  • Js memory leak scenario, how to monitor and analyze