javascript - Three ways to write js anonymous functions
漂亮男人
漂亮男人 2017-05-19 10:39:41
0
3
540

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))
漂亮男人
漂亮男人

reply all(3)
刘奇

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

某草草

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.

大家讲道理

The first one runs the fastest
The last two are beautiful

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template