Possible Duplicate:
What does the exclamation mark do before the function?
If you look at the source code for KnockoutJS 2.1.0 you will see a code structure like this start on line 7:
!function(factory) { ... }(factoryDefinition);
The not operator causes this expression to evaluate to true
rather than undefined
, but why bother?
Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
Answer : A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.
Nope, anonymous functions are used all over the place in JavaScript across the web. It may make debugging a little more difficult in spots, but not nearly enough to say that they shouldn't be used. For example, JQuery makes extensive use of them.
The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .
This is a concise way to form an immediately executed function expression.
Traditionally, people have used these two forms
(function(){ }()); // Recommended by Crockford
(function(){ })(); // What most people use
If you try to just use
function(){ }(); // Syntax error
it will be a syntax error, because it is interpreted as a function declaration rather than an expression. This is why you would need to wrap the function in parentheses.
But if you put a unary operator before the function declaration, you don't have to add a cosing parentheses, and it chops off one character of the code, which is a (very) tiny performance benefit. There are several unary operators that can be used for this same purpose
!function(){ }();
~function(){ }();
-function(){ }();
+function(){ }();
Because if you don't do something then it looks like a syntax error:
function(factory) { ... }(factoryDefinition);
Try it.
It's necessary to get the parser to a point where it expects an expression, so that the function
keyword is recognized in that context. Otherwise, when the parser sees function
as the first token in a statement, it expects a simple function declaration, and that can't be followed by a parenthesized argument list.
There are various alternatives, around each of which cluster various opinions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With