The ambiguity of the parentheses "()" in Javascript

Source: Internet
Author: User

Javascript Small brackets have 5 semantics

Semantic 1: Parameter table when function declaration

1 function func (arg1, arg2) {
2//...
3}


Semantic 2: Used in conjunction with some statements to achieve certain qualifiers


1//And for use
2 for (var a in obj) {
3//...
4}
5
6//And if used together
7 if (boo) {
8//...
9}
10
11//And while working together
while (Boo) {
13//...
14}
15
16//And do while working together
do{
18//...
}while (Boo)


Note: When used with the IF, while, and do, the parentheses implicitly convert the result of the expression into a Boolean value. See implicit type conversions everywhere.



Semantics 3: Used with new to pass values (arguments)

Assuming that the class person is already defined, it has two field names (name), age
var p1 = new Person (' Jack ', 26);


Semantics 4: The invocation operator as a function or an object method (if a parameter is defined, it can be passed as an argument with semantic 3)

Assume that the function func has been defined
Func ();

Assume that the object obj is already defined and has the Func method
Obj.func ();
The typeof operator is mentioned here, and some people like to use it:

typeof (XXX);

Note that the parentheses after typeof are not semantic 4 (that is, not function calls), but rather the semantics 5 that are mentioned later. I use typeof generally without the parentheses in the back.
See also four ways to call named functions.



Semantics 5: Enforcing expression operations

As for semantic 5, the most familiar is the use of eval to parse JSON

1 function Strtojson (str) {
2//Eval strings are added with the mandatory operator ()
3 var json = eval (' (' + str + ') ');
4 return JSON;
5}
Another example is the use of anonymous function self-executing

1 (function () {
2//...
3}) ();
Note that the first pair of parentheses in the above code is semantic 5, while the second pair is semantic 4.

The ambiguity of the parentheses "()" in Javascript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.