Ambiguity in the 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
12345678 |
if ( condition ) { //... } else { //... } for () { //... } |
Semantics 2, Object Direct Volume declaration
1234 |
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
1234567 |
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
1234567 |
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
12 |
function (){}() //匿名函数立即执行, 语法分析期报 {}.constructor //获取对象直接量的构造器,语法分析期报错 |
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
The same situation as
It will not be an error.
In fact, JS's "statement precedence" in the mischief, that is, {} is understood as a compound statement block ( semantics 1 ) instead of the object direct amount ( semantics 2 ) or the semantics of the Declaration 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 ), "functions ()" means executing the function, which is executed immediately after the declaration.
({}). constructor//({}) forces the braces to be interpreted as the direct amount of the object ( Semantics 2 ), "object. xx" means to get the member of the object, and the point operator after nature can execute normally.
Ambiguity in the curly braces ' {} ' in JavaScript