Explain JavaScript's anonymous functions in detail

What is an anonymous function: a function without an actual name

The role of anonymous functions:

1. Closures can be implemented through anonymous functions, and the use of detailed closures (knowledge points that must be mastered) will be updated later.

2. Simulate block-level scopes to reduce global variables. When anonymous functions are executed, the variables stored in memory will be destroyed. Using block-level scopes will greatly reduce the problem of naming conflicts, without worrying about confusing global scopes.

Details of anonymous functions:

Declare a normal function:

   function zxx () {
       console.log('good girl')
   }

Remove the name of the function

   function () { // At this point, the browser will report errors
       console.log('good girl')
   }

Properly defined anonymous functions

    (function (){
        // Since the anonymous function is not executed, statements in the body of the anonymous function are not executed.
        console.log("zxx");
    })

When parentheses are added to functions that remove names, they become anonymous functions.

The role of parentheses:

The parentheses divide our expression combinations into blocks, and each block, that is, each pair of parentheses, has a return value. This return value is actually the return value of the expression in parentheses. So when we enclose an anonymous function with a pair of parentheses, it actually returns a Function object of an anonymous function. Therefore, parentheses with anonymous functions are taken as functions with names. So if you add a list of parameters after the reference variable, you will realize the call form of ordinary functions. Popular point is to add parentheses to achieve the same form as a named function.

Anonymous function self-execution, also known as immediate execution function expression (IIFE)

  • One way
    // Anonymous functions without parameters
    (function () {
        console.log('zxx')
    })();

    // Anonymous functions with parameters
    (function (a, b, c) {
        console.log('Parameter one:', a) // Parametric 1: This is where ordinary functions pass parameters.
        console.log('Parameter two:', b) // Parametric 2: I am Parametric 2
        console.log('Parameter three:', c) // Parameter 3: zxx
    })('This is where ordinary functions pass parameters.', 'I'm parameter two.', 'zxx')
  • Mode two
    (function () {
        console.log('zxx')
    }())

Mode three

    !function (zxx) {
        console.log(zxx)
    }('zxx')

Mode four

    let zxx = function (zxx) {
        console.log(zxx)
    }('zxx')

Common usage of IIFE

    IIFE Another very common advanced use is to use them as function calls and pass parameters in.
    var a = 2;
    (function IIFE (global) {
        var a = 3
        console.log(a) // 3
        console.log(global.a) // 2
    })(window)
    console.log(a) // 2

    IIFE Another change is to invert the order in which the code runs, putting the functions that need to be run in the second place. IIFE Pass in as a parameter after execution
    var a = 2;
    (function IIFE (def) {
        def(window)
    })(function def (global) {
        var a = 3
        console.log(a) // 3
        console.log(global.a) // 2
    })

Application scenarios for anonymous functions

    1.Event
    $('#zxx').onclick = function () {
        console.log('Add click events to buttons')
    }

    2.object
    var obj = {
        name: 'zxx',
        zxx: function () {
            return this.name + ' is' + ' good girl'
        }
    }
    console.log(obj.fn()) // zxx is good girl
    
    3.Functional expression
    var zxx = function () {
        return 'zxx is good girl'
    }
    console.log(zxx()) // zxx is good girl

    4.Callback function
    setInterval(function () {
        console.log('zxx is good girl')
    }, 1000)

    5.Return value as function
        function zxx () {
        // Returns an anonymous function
        return function () {
            return 'zxx'
        }
    }
    console.log(zxx()()) // zxx

Anonymous functions mimic block-level scopes

    if (true) {
        var a = 12 // A is a global variable
    }
    console.log(a) // 12

    for (var i = 0; i < 3; i++) {
        console.log(i)
    }
    console.log(i) // 4
    if () {}for () {} Wait for no scope of their own. If so, the declared variable will be destroyed immediately after its scope has been determined. But block-level scopes can be simulated by anonymous functions:

    function fn () {
        (function () { // Here is our block scope (private scope) 
            var zxx = 'good girl!' // This variable is not externally defined
            console.log(zxx) // good girl!
        })()
        console.log(zxx) // Uncaught Reference Error: zxx is not defined
    }
    fn()
    

Disadvantages of anonymous functions

1. Anonymous functions do not display meaningful function names in stack tracing, which makes debugging difficult.

2. If there is no function name, when a function needs to refer to itself, it can only use arguments.callee references that have expired, such as in recursion. Another function that needs to refer to its own example is that the event listener needs to unbind itself after the event is triggered.

3. Anonymous functions omit function names that are important for code readability/comprehensibility. A descriptive name can make the code self-evident.

 

 

Posted by McChicken on Thu, 19 Sep 2019 00:05:05 -0700