Are Expression Closure and Function Call Identical in JavaScript?
In JavaScript, the following code snippets appear to produce identical output:
<code class="js">(function() { bar = 'bar'; alert('foo'); })(); (function() { bar = 'bar'; alert('foo'); }());</code>
Both blocks execute the alert('foo') statement and declare a variable bar accessible outside the closure. The only apparent difference lies in the closure's syntax, using )()} versus }());.
Are these constructs functionally equivalent?
Answer: Yes, they are identical.
Additional Considerations:
If additional parentheses are introduced, the behavior changes. Consider the following scenarios:
Scenario 1:
<code class="js">new (function() { this.prop = 4; })().prop;</code>
This expression creates a new instance of the function's class and accesses the prop property of the new instance, returning the value 4. It is equivalent to:
<code class="js">function MyClass() { this.prop = 4; } new MyClass().prop;</code>
Scenario 2:
<code class="js">new ( function() { return { Class: function() { } }; }() ).Class;</code>
In this case, the new expression instantiates the Class property of the function's return value. The parentheses around the function call are crucial, indicating that the function should be invoked immediately.
This is equivalent to:
<code class="js">var namespace = { Class: function() { } }; function getNamespace() { return namespace; } new ( getNamespace() ).Class; // Or, new namespace.Class;</code>
If the parentheses were removed from the call to getNamespace(), the expression would instantiate the getNamespace class and access the Class property of the new instance.
The above is the detailed content of Are Parentheses in JavaScript Function Calls and Closures Always Just Syntactic Sugar?. For more information, please follow other related articles on the PHP Chinese website!