Home  >  Article  >  Web Front-end  >  Are \"(function () { }) ()\" and \"(function () { })()\" Functionally Equal in JavaScript?

Are \"(function () { }) ()\" and \"(function () { })()\" Functionally Equal in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 08:53:02854browse

Are

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?

Answer

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".

Differences with Other Syntax

However, when additional syntax is added to the code, differences can emerge.

Case 1: Function Constructor Syntax

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.

Case 2: Namespace Syntax

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn