Give an example:
]
You will know this after trying it The meaning of the code is to declare a function and then execute it immediately. Because the variable scope in Javascript is based on functions, this can avoid variable pollution, but the bit operator "~" here is confusing at first glance. If you remove it and run again, an error will be reported: SyntaxError.
Before explaining why, let us first clarify two concepts in Javascript: function declaration and function expression:
First, let’s take a look at what a function declaration is:
If you need to introduce external Js, you need to refresh to execute
]
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
Now look back at the beginning of the article The question is why an error will be reported after removing the bit operator "~". This is because from the perspective of syntax analysis, Javascript does not allow the use of parentheses directly after the function declaration, while function expressions do not have this restriction. Adding a "~" operator in front of a function declaration allows the syntax parser to treat the following as a function expression. Similarly, adding "!, , -" and other operators in front of a function declaration is also feasible.
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
Although from the perspective of syntax analysis There seems to be no problem, but the above code has drawbacks. It introduces a variable, which may pollute the existing operating environment and cause potential problems.
<script>
~function() {
alert("hello, world.");
}();
</script>[Ctrl A Select all Note: <script>
function() {
alert("hello, world.");
};
function foo() {
alert("hello, world.");
};
</script>If you need to introduce external Js, you need to refresh to execute it <script>
var foo = function() {
alert("hello, world.");
};
</script>]<script>
var foo = function() {
alert("hello, world.");
}();
</script> <script>
(function() {
alert("hello, world.");
})();
</script>I understand the principle, no matter No matter what writing method you encounter, Monk Zhanger will no longer be confused.