To you: Execute the function immediately: (function () {...}) () and (function () {...} ()) What is the difference between ... __ function

Source: Internet
Author: User

1. the traditional method definition (statement) is implemented as follows:

function foo () {...} This is a definition; the definition simply lets the interpreter know it exists, but it does not run.
Foo (); This is the statement, and the interpreter encounters the statement that will run it.

Note:(1) Traditional methods are cumbersome, definition (declaration) and execution separate, (2) Traditional methods directly pollute the global namespace.

2. the currently more popular approach is defined as follows:

function foo () {...}) ();

Or

(function foo () {...} ());

3. In addition, the above writing, there are many other writing, such as:
!function foo () {...} ();

Or

+function foo () {...} ();

That's all you can do. That is, +function () {} or!function foo () {} is equal to (function () {}).

* Summary

A. (function () {}) (); is to parse the function as an expression and then perform the parsed function, which is equivalent to var a = function () {}; A (); A gets the function.
B. (function () {} ()); is to execute the function expression and execution as a statement directly, the equivalent of var a = function () {} (); A what gets is the result.
The end result is the same for both of these methods.
C. General use (function () {}) has a role in the avoidance of global variables;

Note: The so-called do not pollute the global namespace, because the two definitions above create a new function scope, your real business code is encapsulated in it, naturally will not touch the global object.

If you need a global object, pass the parameters as follows:

void function (Global) {
    //Here, Global is the Universal Object
} (this)    //In the browser, this is the Window object


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.