JavaScript has a lot of interesting uses and can be found in Google Code search, for example:
<script>~function () { alert ("Hello, World");} ();</script>
Try to know that the meaning of this code is to declare a function, and then immediately execute, because the scope of variables in JavaScript is based on function, so this can avoid the variable pollution, but here the bitwise operator "~" At first glance let a person cannot touch the mind, If you remove it and run it, you will get an error: SyntaxError.
Before explaining why, let's first clarify two concepts in javascript: function declaration and function expression:
Let's take a look at what a function declaration looks like:
<script>function () { alert ("Hello, World");}; function foo () { alert ("Hello, World");}; </script>
Let's look at what the function expression is:
<script>var foo = function () { alert ("Hello, World");}; </script>
Now look back to the article at the beginning of the question, why the removal of the bitwise operator "~" After the error, because from a syntactic perspective, JavaScript is not allowed to use the parentheses directly after the function declaration, and the function expression does not have this restriction, by adding a "~" operator before the function declaration, It is possible for the parser to think of the latter as a function expression, as well as the addition of "!,+,-" operators in front of the function declaration.
So why don't we use the following function expressions?
<script>var foo = function () { alert ("Hello, World");} ();</script>
Although there is no problem from the point of view of syntax parsing, the above code is flawed, introducing a variable that may contaminate the existing operating environment and pose potential problems.
The use of the bitwise operator "~" is a bit artifice, in fact, the function declaration with parentheses to make it easier to read:
<script> (function () { alert ("Hello, World");}) ();</script>
Understand the principle, no matter what writing, will not confused again.
This entry is posted in Technical and tagged Javascript by Lao Wang. Bookmark the permalink.
8 Thoughts on "function declarations and function expressions in JavaScript"
Http://huoding.com/2011/03/02/48
function declarations and function expressions in "javascript" javascript