Execute function immediately

Source: Internet
Author: User

First, JS immediately execute the function of the wording



Way 1, the last parenthesis

(function () {alert (1);} ());


Mode 2, function outside parentheses

(function () {alert (1);}) ();


Mode 3, function front plus operator, common is! with void

!function () {alert (1);} ();
void function () {alert (2);} ();


Second, immediately execute the parameters of the function

Arguments can be passed to an immediate execution function, such as

(function (who, when) {
    Console.log ("I met" + Who + ' on ' + when);
} ("Joe Black", New Date ()));

Remember:

1, immediately inside the function can access external variables, so in many cases, we do not need to pass parameters. such as: jquery window arguments, if not passed in. The interior is also available for direct use.

2. Usually you should not pass too many functions to the immediate execution function, because it will soon become a burden--in order to understand how the code works, you have to scroll the source code up and down frequently.



Third, immediately execute the return value of the function

Like any other function, an immediate execution function can return a value and can be copied to other variables, such as


var result = (function () {
return 2 + 2;
}());


var result = (function () {
return 2 + 2;
})();

Execute function immediately

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.