Background
When writing an auto-execute function
vm.$watch(‘datas‘, function() { console.log(vm.datas);})(function () { console.log(‘test‘);})()
An inexplicable error occurred:
Uncaught typeerror:vm. $watch (...) (...) is not a function
Workaround:
vm.$watch(‘datas‘, function() { console.log(vm.datas););(function () { console.log(‘test‘);})()
A semicolon is done.
Since then, we have introduced the classic topic of the JavaScript code to add semicolons.
Semicolon
In C, a semicolon is a sign of the end of a statement and must end with a semicolon where the statement ends. The semicolon is optional, and the semicolon can be omitted if the statement has one row.
ASI mechanism (Automatic semicolon insertion)
The ASI mechanism in JavaScript allows us to omit semicolons. The ASI mechanism does not say that the parser automatically adds the semicolon to the code in the parsing process, but that the parser, in addition to the semicolon, will use a certain rule as the basis for the segmentation, thus guaranteeing the correctness of the parsing.
ASI rules
Attention
- The new line
(
[
/
+
-
*
%
,
.
begins, it's easy to parse with the previous line of code without semicolons as a whole, which is obviously not the result we want.
Conclusion
To enhance code readability and reduce ambiguity, personal opinion is to add a semicolon at the end of the statement
Ps:
- Do not place
++
or --
put on the same line
- If
return
there is a parameter, do not place the argument in a separate row
- Do not place the beginning of the parenthesis on a new line, for the previous
JS code in the end plus no semicolon