Javascript has a lot of interesting usage, which can be found in GoogleCodeSearch. Today, I have seen it from the huoding notes, which is very good. I suggest you read it. For example:
Script ~ Function () {alert ("hello, world.") ;}(); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
If you try this code, it means to declare a function and execute it immediately. Because the variable scope in Javascript is based on the function, this can avoid variable pollution, but here the bitwise operator "~" At first glance, people cannot understand it. If you remove it and run it again, an error will be reported: SyntaxError.
Before explaining why, let's clarify two concepts in Javascript: function declaration and function expression:
Let's take a look at the function declaration:
Script function () {alert ("hello, world.") ;}; function foo () {alert ("hello, world.") ;}; script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Let's take a look at what kind of function expressions are:
Script var foo = function () {alert ("hello, world.") ;}; script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Now let's look back at the question at the beginning of the article. Why do we remove the bitwise operator "~"? An error is reported during subsequent running. This is because Javascript cannot directly use parentheses after function declaration from the perspective of Syntax Parsing, but function expressions do not have this restriction, add "~" before the function declaration Operator, you can let the syntax parser regard it as a function expression. Similarly, add "!, +,-"And other operators are also feasible.
So why don't we use the following function expression?
Script var foo = function () {alert ("hello, world.") ;}(); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Although there is no problem from the perspective of Syntax Parsing, the above Code has drawbacks. It introduces a variable, which may pollute the existing runtime environment and bring potential problems.
Use the bitwise operator "~" In fact, the function declaration is more readable with parentheses:
Script (function () {alert ("hello, world.") ;}) (); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
After understanding the principle, no matter what writing method you encounter, you will not be confused by the second monk.