Home > Web Front-end > JS Tutorial > Parsing the ambiguity of Javascript parentheses '()'_javascript skills

Parsing the ambiguity of Javascript parentheses '()'_javascript skills

WBOY
Release: 2016-05-16 17:10:58
Original
1640 people have browsed it

There are five semantics of parentheses in Javascript

Semantics 1, parameter list when function is declared

Copy code The code is as follows:

function func(arg1,arg2){
// ...
}

Semantic 2, used in combination with some statements to achieve certain restrictions Function
Copy code The code is as follows:

// Use 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 replace the expression in it The result is implicitly converted to a Boolean value. See Implicit Type Conversions in JavaScript.

Semantic 3, used with new to pass values ​​(actual parameters)

Copy code The code is 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 code The code is 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 like this

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 code The code is 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 the anonymous function self-execution
Copy code The code is as follows:

(function(){
// ...
})();
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template