search

Home  >  Q&A  >  body text

javascript - Three ways to write js anonymous functions

The following is the anonymous function of JS. What are the differences between these three forms? What are the characteristics of each?

// 形式1
        (function(a){
            console.log(a);

        })(33)
        // 形式2
        !function(){
            console.log(2222222222)
        }()
        // 形式3
        (function(a){
            console.log(a);
        }(100))
漂亮男人漂亮男人2787 days ago592

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-05-19 10:41:41

    There is actually no essential difference between these three ways of writing. They are all for the compiler (interpreter) to treat function(a){ console.log(a) } and () as a whole for execution. It's probably more of a difference in habits. Personally, I prefer the first one, as it makes sense logically. Some people like the second method, using () to enclose the entire function call. This can more directly indicate that this code is a whole. I heard that foreigners like to use it! Or void

    reply
    0
  • 某草草

    某草草2017-05-19 10:41:41

    The first is a common way of self-executing functions. What is wrapped in parentheses is the function body itself, which means that the function definition is executed and a function is returned. The following parentheses indicate that the parameters are passed in and the function is executed.
    The second and third methods are actually the same. They use !括号 to "wrap" the function body and add the parameter part respectively, both of which indicate the execution of this code block. When executing the code block, the name of the function can be omitted.
    The difference between the second and third methods is that the former has no parameters and returns a Boolean value after negating the function execution result, while the latter has parameters and returns the function return value by default.

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-19 10:41:41

    The first one runs the fastest
    The last two are beautiful

    reply
    0
  • Cancelreply