Home > Web Front-end > JS Tutorial > Are Parentheses in JavaScript Function Calls and Closures Always Just Syntactic Sugar?

Are Parentheses in JavaScript Function Calls and Closures Always Just Syntactic Sugar?

DDD
Release: 2024-11-02 20:33:31
Original
535 people have browsed it

Are Parentheses in JavaScript Function Calls and Closures Always Just Syntactic Sugar?

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

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

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

Scenario 2:

<code class="js">new ( function() {
    return { Class: function() { } }; 
}() ).Class;</code>
Copy after login

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template