This is the ninth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Application of closures

3.1 Using closures to achieve modular development

3.1.1 Module Mode

Encapsulates private variables and methods while exposing only one interface for external invocation.

function cool() {
  let a = "cool";
  let b = [1.2.3];
  function doA() {
    console.log(a);
  }
  function doB() {
    console.log(b.join("!"));
  }
  return {
    doA: doA,
    doB: doB,
  };
}
let foo = cool();
foo.doA(); //cool
foo.doB(); / / 1! 2! 3
Copy the code

Cool () returns an object in object literal syntax

This object contains references to internal functions rather than internal data variables, keeping the internal data variables hidden and private.

The doA() and doB() functions have closures that cover the inner scope of the module instance, and closures are created when the function is passed out of the lexical scope by returning an object containing a property reference.

  • The module pattern must have an external enclosing function, which must be called at least once (each call creates a new module instance)
  • The enclosing function must return at least one inner function so that the inner function can form a closure in the private scope and can access or modify the private state.

3.1.2 Singleton mode

let foo = (function cool() {
  let a = "cool";
  let b = [1.2.3];
  function doA() {
    console.log(a);
  }
  function doB() {
    console.log(b.join("!"));
  }
  return {
    doA: doA,
    doB: doB, }; }) (); foo.doA();//cool
foo.doB(); / / 1! 2! 3
Copy the code

To convert a module function to IIFE, call the function immediately and assign the return value directly to the singleton’s module instance identifier foo

3.2 Simulating block-level scope with closures

var data = [];
for (var i = 0; i < 3; i++) {
  (function () {
    var j = i;
    data[j] = function () {
      console.log(j); }; }) (); } data[0] ();/ / 0
data[1] ();/ / 1
data[2] ();/ / 2
Copy the code

Four, the advantages and disadvantages of closures

4.1 the advantages

  1. The cache. Hide variables from GC collection.
  2. Realize currying. Use the closure feature to accomplish currying.

We can implement a counter using closures without worrying about global variable contamination:

function foo() {
  let num = 0;
  return function() {
    num++;
    console.log(num);
  };
}
const f = foo();
f(); / / 1
f(); / / 2
Copy the code

4.2 disadvantages

  1. Memory consumption. A variable generated by a closure cannot be destroyed.
  2. Performance issues. Because the internal variables of the closure have a higher priority than the external variables, one level of the scope chain needs to be searched multiple times, which affects the search speed to some extent.
function assignEvent() {
  let id = "123";
  document.getElementById("save-btn").onclick = function (event) {
    saveDocument(id);
  };
}
Copy the code