There are five semantics of parentheses in Javascript
Semantics 1, parameter list when function is declared
Copy the code code as follows:
function func(arg1,arg2){
// ...
}
Semantic 2, used in conjunction with some statements to achieve certain limiting effects
Copy the code code as follows:
// used with for in
for(var a in obj){
// ...
}
// used with if
if(boo){
//...
}
// used with while
while(boo){
// ...
}
// used with do while
do{
// ...
}while(boo)
Note: When used with if, while and do while, parentheses will implicitly convert the expression result into a Boolean value. See Implicit Type Conversion in JavaScript.
Semantic 3, used with new to pass values (actual parameters)
Copy the code code as follows:
// Assume that the class Person has been defined, which has two fields name (name) and age (age)
var p1 = new Person('Jack',26);
Semantic 4, as a call operator for functions or object methods (if parameters are defined, actual parameters can also be passed in the same way as Semantic 3)
Copy the code code as follows:
// Assume that the function func has been defined
func();
// Assume that the object obj has been defined and has the func method
obj.func();
Here is the typeof operator, some people like to use it this way
typeof(xxx);
Please note that the parentheses after typeof are not semantic 4 (that is, not a function call), but semantic 5 mentioned later. I usually use typeof without the following parentheses.
Semantics 5, forced expression evaluation
Regarding Semantic 5, everyone is most familiar with using eval to parse JSON.
Copy the code code as follows:
function strToJson(str){
// Force operators () are added on both sides of the string in eval
var json = eval('(' + str + ')');
return json;
}
Another example is that anonymous functions are often used for self-execution.
Copy the code code as follows:
(function(){
// ...
})();