Parsing the polysemy of the Javascript parenthesis 'of'

  • 2020-03-30 00:41:41
  • OfStack

Javascript brackets have five semantics

Semantics 1, function declaration when the parameter table

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

Semantics 2, used in conjunction with statements to achieve certain qualifiers

//Used with for in
for(var a in obj){ 
  // ... 

//Use it with if

//Use it with while
  // ... 

//Used with do while
  // ... 

Note: when used with if, while, and do while, the parentheses implicitly convert the result of the expression into a Boolean value. See implicit type conversion in JavaScript.

Semantics 3, used with new to pass values (arguments)

//Let's say I've defined the class Person, and it has two fields name, age
var p1 = new Person('Jack',26); 

Semantics 4, as a function or object method call operator (if defined parameters can also be passed as semantics 3)

//Let's say I've defined the function func

//Assume that you've defined the object obj and have the func method

Here's the typeof operator, which some people like to use

The typeof (XXX);

Note that the parentheses after typeof are not semantics 4 (that is, not a function call), but semantics 5 as mentioned later. I use typeof without the usual parentheses.

Semantic 5, force expression operation

The most familiar thing about semantic 5 is that you use eval to parse JSON

function strToJson(str){ 
     //In eval, we have the forced operator () on both sides of a string
     var json = eval('(' + str + ')');  
     return json; 

Another example is the use of more anonymous function self - execution

  // ... 

Related articles: