Absrtact: This article mainly introduces four kinds of semantic functions of curly braces in JavaScript.
There are four semantic functions of the curly braces in JS
Semantic 1, the organization of compound statements, which is the most common
if (condition) { //...} else { //...} for () { //...}
Semantics 2, Object Direct Volume declaration
var obj = {name: ' Jack ', age:23};
The whole is an assignment statement, where {name: ' Jack ', age:23} is an expression.
Semantics 3, declaring a function or function direct amount
Function F1 () {//...} var F2 = function () {//...}
The difference between F1 and non-F2 is that the former is in the grammatical interpretation period, the latter in the running period. The difference is that if the code calling the function is after the function definition, then there is no difference; if the code calling the function is before the function definition, then F1 can still be called, and F2 will error, prompting F2 undefined.
Semantic 4, Syntax notation for structured exception handling
try {//...} catch (ex) {//...} finally{//...}
There is a difference between the curly brace and the conforming statement ( Semantics 1 ), if there is only one statement in the curly braces, the curly braces can be omitted in the if/else/for, but try/catch/finally cannot be omitted.
The following code tangled even n long
function () {} ()//anonymous function immediate execution, parsing period (}.constructor//) constructor to get direct amount of object, parsing period error
It is puzzling why [].constructor writes without error, a constructor that wants to get the direct amount of the object, and a constructor that gets the direct amount of the array.
Of course, add a variable to receive will not error
var c = {}.constructor;
The same situation as
The var fn = function () {} () does not error.
In fact, JS's statement takes precedence over the mischief, that is, {} is understood as a compound statement block ( semantics 1 ) instead of the object's direct amount (Semantics 2 ) or the semantics of the declared function ( semantics 3 ).
function () {} (), the curly brace is interpreted as a compound statement, and the function () in front of nature declares that the syntax of the functions is incomplete resulting in a parsing period error. {}.constructor, curly braces are interpreted as compound statements, the braces are followed by dot operators, and there is no reasonable object before the dot operator.
Fixes are well known: Add a mandatory operator ()
(function () {}) (), (function () {}),//force it to be understood as a function ( semantics 3 ), which means to execute the function, which is executed immediately after the declaration.
({}). constructor//({}) forces the braces to be interpreted as the object's direct amount ( semantics 2 ), the object. XX means to get the member of the object, and the point operator after nature can execute normally.
Author: snandy original link
Ambiguity in the curly braces ' {} ' in JavaScript