Are Anonymous Functions with Different Syntax Functionally Equal in JavaScript?
In JavaScript, both (function() { })() and (function() { }()) may appear to perform the same task by displaying "foo" and "bar" in succession. However, under certain conditions, there are subtle differences between these two syntaxes.
Code Block 1:
(function() { bar = 'bar'; alert('foo'); })(); alert(bar);
Code Block 2:
(function() { bar = 'bar'; alert('foo'); }()); alert(bar);
Functionally Equivalent
In the absence of any modifications, both code blocks are functionally equivalent. They create an anonymous function, execute it immediately, and then access the bar variable defined within the function.
Differences with Modifications
However, if you introduce a modifier such as new before the function calls or add something after them, the behavior changes.
Code Block 1 with new and .prop:
new (function() { this.prop = 4; }) ().prop;
This code creates a new instance of the anonymous function and accesses its prop property. It returns 4.
Code Block 2 with new and .Class:
new ( function() { return { Class: function() { } }; }() ).Class;
In contrast, this code calls new on the Class property. Due to the additional parentheses inside the outer parentheses, the function call is not part of the new expression. It instead calls the function normally and returns its return value, which is a class instance.
In summary, while both (function() { })() and (function() { }()) are functionally equivalent under normal conditions, they behave differently when combined with modifiers that affect how they are executed.
The above is the detailed content of Do Anonymous Functions with Different Syntax Behave Differently in JavaScript When Combined with Modifiers?. For more information, please follow other related articles on the PHP Chinese website!