Application of closures of JavaScript advanced day34~36-- functions

1. Application of closures: define JS modules

  • js files with specific functions
  • Encapsulate all data and functions inside a function (private)
  • Expose only one object or function that contains n methods
  • The user of the module only needs to call the method through the exposed object of the module to realize the corresponding function

Method 1: prepare a mymodule JS file:

function myModule() {
  //Private data
  var msg = 'My atguigu'
  //Functions that manipulate data
  function doSomething() {
    console.log('doSomething() '+msg.toUpperCase())
  }
  function doOtherthing () {
    console.log('doOtherthing() '+msg.toLowerCase())
  }
//Use object encapsulation when you need to expose multiple methods
  //Expose objects outward (Methods for external use)
  return {
    doSomething: doSomething,
    doOtherthing: doOtherthing
  }
}

Closures are used in this js

Call in html:
First introduce
Then call the method through the object

<script type="text/javascript" src="myModule.js"></script>
<script type="text/javascript">
  var module = myModule()
  module.doSomething()
  module.doOtherthing()
</script>

Mode 2 (recommended): when there is no module JS is exposed by using anonymous function self Calling:

//Customize through anonymous functions
(function () {
  //Private data
  var msg = 'My atguigu'
  //Functions that manipulate data
  function doSomething() {
    console.log('doSomething() '+msg.toUpperCase())
  }
  function doOtherthing () {
    console.log('doOtherthing() '+msg.toLowerCase())
  }

  //Add the method to the window to expose it
  window.myModule2 = {
    doSomething: doSomething,
    doOtherthing: doOtherthing
  }
})()

Directly use in html through js file:

<script type="text/javascript" src="myModule2.js"></script>
<script type="text/javascript">
  myModule2.doSomething()
  myModule2.doOtherthing()
</script>

2. Disadvantages of closures

  • After the function is executed, the local variables in the function are not released, and the memory consumption time will become longer
  • Easy to cause memory leakage (memory occupied but not used)

3. Closure solution

  • You don't have to close it
  • Timely release
<script type="text/javascript">
  function fn1() {
    var arr = new Array[100000]
    function fn2() {
      console.log(arr.length)
    }
    return fn2
  }
  var f = fn1()
  f()

  f = null //!!!! Make internal functions garbage objects -- > recycle closures
</script>

4. Memory overflow

  • An error in the operation of a program
  • When the memory needed by the program exceeds the remaining memory, a memory overflow error is thrown
  var obj = {}
  for (var i = 0; i < 10000; i++) {
    obj[i] = new Array(10000000)
    console.log('-----')
  }

5. Memory leakage

  • The occupied memory is not released in time. You can continue to run without error
  • Excessive accumulation of memory leaks can easily lead to memory overflow
  • Common memory leaks:
    • Unexpected global variable
    • Timers or callback functions that are not cleaned up in time
    • closure
   // Unexpected global variable
  function fn() {
    a = new Array(10000000)//var should be used to define variables to avoid becoming a global variable
    console.log(a)
  }
  fn()
// Timers or callback functions that are not cleaned up in time
  var intervalId = setInterval(function () { //Do not clean after starting the cycle timer
    console.log('----')
  }, 1000)
// clearInterval(intervalId) / / use clearInterval to clean up the timer
    // closure
  function fn1() {
    var a = 4
    function fn2() {
      console.log(++a)
    }
    return fn2
  }
  var f = fn1()
  f()

  // f = null  //!!!! Make internal functions garbage objects -- > recycle closures

6. Closure related interview questions

Call object Getnamefunc() returns a function function
Execute function() to return this Name returns global variables through method calls (returns local variables through object calls)

  var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;
      };
    }
  };
  alert(object.getNameFunc()());  //  the window

Call object Getnamefunc() returns a function function
Execute function() to return that name
Since that saves the value of the calling getNameFunc object, the local variable my object is returned
With closures – that

  var name2 = "The Window";
  var object2 = {
    name2 : "My Object",
    getNameFunc : function(){
      var that = this;//!! Often use a variable to save the this object of the current calling function.
      return function(){
        return that.name2;
      };
    }
  };
  alert(object2.getNameFunc()()); //?  my object

Here is the reference

function fun(n,o) {
 console.log(o)
 return {
 fun:function(m){
 return fun(m,n);
 }
 };
 }
 var a = fun(0); a.fun(1); a.fun(2); a.fun(3);//undefined,?,?,?
 var b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,?
 var c = fun(0).fun(1); c.fun(2); c.fun(3);//undefined,?,?,?

Note:
The first layer and the third layer are the same function, and the second layer is different function
In question 2 And;, One is to continue the call, the other is to end the statement, and the assignment retains the current state
Specific analysis can Click to view

Keywords: Javascript

Added by jerrylouise on Thu, 20 Jan 2022 20:09:02 +0200