Self-executed anonymous function! Function ()

Source: Internet
Author: User

If I have been free recently, Let me calm down and look at various codes. The frequent appearance of functions and exclamation points reminds me of the last time I attended a team meeting in Hangzhou two months ago, @ The same question thrown out by Xi Zijian Ying:If you add an exclamation point (!) before the function (!) What will happen? For example, the following code:

!function(){alert(‘iifksp‘)}()        // true

It is easy to understand why the value true is obtained after running on the console. Because this anonymous function does not return a value, the returned value is undefined by default, and the result of the inversion is true naturally. So the question is not about the result value, but about why the reverse operation makes the self-tuning of an anonymous function legal?

We may be more accustomed to adding parentheses to call anonymous functions:

(function(){alert(‘iifksp‘)})()        // true

Or:

(function(){alert(‘iifksp‘)}())        // true

Although the positions of the brackets are different, the effect is the same.

So what are the benefits that many people have a special liking for this exclamation point? It is unnecessary to save a single character. This means that even a K library will not save much space. Since it is not a space, it may be time-based consideration. It is hard to tell the truth. performance is mentioned at the end of the article.

Back to the core question, why? Even more importantly, why is this necessary?

In fact, whether it is a bracket or an exclamation point, there is only one thing that makes the entire statement legal, that isConverts a function declaration statement into an expression..

function a(){alert(‘iifksp‘)}        // undefined

This is a function declaration. If you directly add brackets after such a declaration, the parser will naturally not understand and report an error:

function a(){alert(‘iifksp‘)}()        // SyntaxError: unexpected_token

Because such code obfuscated the function declaration and function call, function a declared in this way should be called in a (); method.

But the brackets are different. It converts a function declaration into an expression. The parser no longer processes function a in the form of a function declaration, but is processed as a function expression, therefore, it can be accessed only when the program executes function.

So,Any method to eliminate the ambiguity between function declaration and function expression can be correctly recognized by the parser.. For example:

var i = function(){return 10}();        // undefined
1 && function(){return true}();        // true
1, function(){alert(‘iifksp‘)}();        // undefined

Assign values, logic, and even Comma. All operators can tell the parser that this is not a function declaration. It is a function expression. In addition, The unary operation of the function can be regarded as the fastest way to eliminate ambiguity. Exclamation points are only one of them. If you do not care about the returned valuesMona1 operations are valid.:

!function(){alert(‘iifksp‘)}()        // true
+function(){alert(‘iifksp‘)}()        // NaN
-function(){alert(‘iifksp‘)}()        // NaN
~function(){alert(‘iifksp‘)}()        // -1

Even the following keywords can work well:

void function(){alert(‘iifksp‘)}()        // undefined
new function(){alert(‘iifksp‘)}()        // Object
delete function(){alert(‘iifksp‘)}()        // true

Finally, parentheses do the same thing. eliminating ambiguity is what it really does, rather than taking functions as a whole, therefore, it is legal to include both the brackets in the Declaration and the entire function:

(function(){alert(‘iifksp‘)})()        // undefined
(function(){alert(‘iifksp‘)}())        // undefined

After talking about this, we are talking about some of the most basic concepts-statements, expressions, and expression statements. These concepts are as confusing as pointers and pointer variables. Although this obfuscation has no effect on programming, it is a stumbling block that may cause a burst of blood at any time.

Finally, we will discuss the performance. I have created a test on jsperf: http://jsperf.com/js-funcion-expression-speed. you can run the test results using different browser hosts. I also listed the results in the following table (because I am poor, the test configuration is a bit embarrassing, but there is no way: Pentium dual-core 1.4 GB, 2 GB memory, win7 Enterprise Edition ):

It can be seen that the results produced by different methods are not the same, and the results vary greatly, depending on the browser.

However, we can still find many commonalities:The new method is always the slowest-- This is taken for granted. There are not many gaps in other aspects, but it is certain that exclamation points are not the best choice. On the other handTraditional brackets always show fast performance in testsIn most cases, it is faster than the exclamation point. Therefore, we usually use the best method.Addition and subtraction are amazing in chromeIn addition, it is widely used in other browsers, and the effect is better than the exclamation point.

Of course, this is only a simple test and cannot be explained. However, some conclusions make sense: parentheses and minus signs are optimal.

But why do so many developers love exclamation points? I think this is just a habit, and the advantages and disadvantages between them can be completely ignored. Once you get used to a code style, this convention will make the program readable from chaos. If you get used to exclamation points, I have to admit that it is more readable than parentheses. I don't have to pay attention to the matching of parentheses while reading, or forget it when writing --

<Transferred from: · (because no one else has written the source) ·>

Self-executed anonymous function! Function ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.