Home >Web Front-end >JS Tutorial >Parsing the ambiguity of braces '{}' in Javascript_javascript skills
Braces in JS have four semantic functions
Semantics 1, organize compound statements, this is the most common
Semantic 3, declare function or function literal
Semantics 4, syntax symbols for structured exception handling
I have struggled with the following code for a long time
Of course, adding a variable to receive will not cause an error
var c = {}.constructor;
Same situation as
var fn = function(){}(), no error will be reported.
It is actually the "statement priority" of js that is causing trouble, that is, {} is understood as a compound statement block (semantic 1) rather than the semantics of an object literal (semantic 2) or a declared function (semantic 3).
function(){}(), curly brackets are understood as compound statements. Naturally, the syntax of the previous function() declaration function is incomplete, causing an error during syntax analysis.
{}.constructor, the curly braces are understood as compound statements, and the curly braces are followed by the dot operator. If there is no reasonable object before the dot operator, an error will naturally be reported.
The fix is well known: add a coercion operator ()
(function(){})(), (function(){});//Force it to be understood as a function (semantics 3), "Function ()" means executing the function, that is, it is executed immediately after declaration.
({}).constructor //({}) forces the curly braces to be understood as object literals (semantic 2). "Object.xx" means to obtain the members of the object. Naturally, the following dot operator can Executed normally.