Home >Web Front-end >JS Tutorial >Are \'(function () { }) ()\' and \'(function () { })()\' Functionally Equal in JavaScript?
In JavaScript, the following two code blocks appear to produce identical results:
(function () { bar = 'bar'; alert('foo'); })(); alert(bar);
(function () { bar = 'bar'; alert('foo'); }()); alert(bar);
Both blocks display the message "foo" followed by "bar". However, is there any functional difference between these two code structures?
Code Blocks Are Identical
Under normal circumstances, "(function () { }) ()" and "(function () { })()" are functionally identical in JavaScript. They both invoke an anonymous function and immediately execute it. The function initializes the bar variable and alerts the message "foo".
However, when additional syntax is added to the code, differences can emerge.
Consider the following code:
new (function () { this.prop = 4; }) ().prop;
This code creates a new instance of the function's class and retrieves the prop property of the new instance. It returns the value 4.
Consider the following code:
new ( function() { return { Class: function() { } }; }() ).Class;
This code invokes the new operator on the Class property. Due to the nested parentheses, the function is invoked normally, and its return value is used to create a new instance.
The above is the detailed content of Are \'(function () { }) ()\' and \'(function () { })()\' Functionally Equal in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!