Parsing the polysemy of the Javascript braces '{}'

  • 2020-03-30 00:42:51
  • OfStack

JS braces have four semantic effects

Semantic 1, organization of compound statements, is the most common

if( condition ) { 
}else { 
for() { 

Semantics 2, object direct quantity declaration

var obj = { 
    name : 'jack', 
    age : 23 

The whole thing is an assignment statement, where {name:'jack',age:23} is an expression.

Semantics 3, declare functions or function direct quantities

function f1(){ 

var f2 = function(){ 

The difference between f1 and non-f2 is that the former is in the parse phase and the latter is in the run phase. The difference is that if the code that calls the function is after the function is defined, there is no difference. If the code that calls this function is before the function is defined, f1 can still be called, and f2 will report an error that f2 is not defined.

Semantics 4, the syntax of structured exception handling

try { 
}catch( ex ){ 

The curly braces here are different from the conformance statement (semantic 1). If there is only one statement in the curly braces, the curly braces can be omitted in the if/else/for, but not in the try/catch/finally.

The following code is entangled for even N long

function(){}() //Anonymous functions are executed immediately and the syntax is parsed
{}.constructor //Gets the constructor of the object's direct quantity

The puzzle is why [].constructor writes this way without reporting an error, one for getting the direct quantities of an object and one for getting the direct quantities of an array.

Of course, adding a variable to receive also does not report an error

Var c = {}. The constructor;

Same thing

Var fn = function(){}().

In fact, it is js's "statement first" that is, {} is understood as a block of compound statements (semantic 1) rather than the semantics of object direct quantities (semantic 2) or declarative functions (semantic 3).

Function (){}(), curly braces are understood as a compound statement, and of course the incomplete syntax of the function() declaration leads to errors in the parse phase.

Constructor, braces are interpreted as a compound statement, followed by a point operator, and an error is reported if there is no reasonable object in front of the point operator.

The fix is well known: add a force operator ()
(function () {}) (), (the function () {}); // force it to be understood as a function (semantics 3), "function ()" means to execute the function, that is, to execute immediately after the declaration.

Constructor //({}). Constructor //({}) forces the braces to be interpreted as an object direct (semantics 2), and "object.

Related articles: