Home > Web Front-end > JS Tutorial > Do Anonymous Functions with Different Syntax Behave Differently in JavaScript When Combined with Modifiers?

Do Anonymous Functions with Different Syntax Behave Differently in JavaScript When Combined with Modifiers?

Susan Sarandon
Release: 2024-10-30 15:17:02
Original
919 people have browsed it

Do Anonymous Functions with Different Syntax Behave Differently in JavaScript When Combined with Modifiers?

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);
Copy after login

Code Block 2:

(function() {
    bar = 'bar';
    alert('foo');
}());

alert(bar);
Copy after login

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;
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template