Home >Web Front-end >JS Tutorial >A problem analysis about javascript anonymous functions_javascript skills

A problem analysis about javascript anonymous functions_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:54:361062browse

An anonymous function is a function without a name. For example:

Copy code The code is as follows:

function (){
alert(' a function');
}

However, the above code will report an error. Firebug prompt: function statement requires a name, that is: the function must have a name.

The strange thing is that if I wrap this unnamed function with a pair of (), no error will be reported. For example:
Copy code The code is as follows:

(function (){
alert( 'a function');
})

(Pay attention to the ()!) that wraps the function. Although this will not report an error, who knows whether the function was declared successfully? Is it because there is no statement at all that the error is not reported? Let’s test like this: let the function execute itself once:
Copy the code The code is as follows:

( function (){
alert('a function');
}())

As you can see, the function is executed, indicating that the function exists.

Similarly, if you remove the () wrapping the function at this time, the previous error will still be reported and the function will not be executed. . .
Copy code The code is as follows:

function (){
alert('a function ');
}()

Is this really so important for () wrapping functions? Can any expert explain the principle?
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn