Function Invocation Syntax in JavaScript: Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" Functionally Identical?
Question:
Consider the following two JavaScript code blocks:
(function() { bar = 'bar'; alert('foo'); })(); alert(bar);
(function() { bar = 'bar'; alert('foo'); }()); alert(bar);
Both code blocks execute alert('foo') and then alert(bar), displaying 'foo' and 'bar' respectively. The sole difference between the two is the syntax of the function invocation. Are they functionally identical?
Answer:
Yes, in general, the two code blocks are functionally equivalent. They will both define a new function, execute it immediately, and then access the bar variable within the global scope.
Exceptions:
However, there are edge cases where the two syntaxes may behave differently. Specifically, if you introduce new code either before the function or after a .something within the function, they will no longer behave identically.
Code 1:
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, returning 4. It is equivalent to:
function MyClass() { this.prop = 4; } new MyClass().prop;
Code 2:
new ( function() { return { Class: function() { } }; }() ).Class;
This code calls new on the Class property. Since the parentheses for the function call are within the outer parentheses, they don't trigger the new expression and instead call the function normally, returning its return value. The new expression instantiates up to the .Class and instantiates that. It is equivalent to:
var namespace = { Class: function() { } }; function getNamespace() { return namespace; } new ( getNamespace() ).Class; //Or, new namespace.Class;
Without parentheses around the call to getNamespace(), this code would be parsed as (new getNamespace()).Class, instantiating the getNamespace class and returning the Class property of the new instance.
The above is the detailed content of Are '(function () { } ) ( )' and '(function () { } ( ) )' Functionally Identical in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!