JavaScript self-execution function __ function

Source: Internet
Author: User
Overview

Since the executive function is also called the call function immediately, as the name implies, can be executed immediately after the function declaration, we read the common JS library (such as jquery) source code, often found from the executive function of the figure, below my understanding. wording

There are two ways to do a self execution function:
The first one is more common:

(function () {
    Console.log ("Method 1");
}) ();

The second type of writing is the JSLint recommendation, which looks more holistic:

(function () {
    Console.log ("Method 2");
} ());

Both of these pieces of code are immediately output when executed. function

Self-executing functions appear to have two functions: the page load needs to do some setup work, such as initialization operations, these tasks do not need to repeat, so do not require a name of the reuse function to do these tasks sometimes need to use some variables, these variables can not pollute the global scope

The following example: We want to implement a function, when the user enters the page, give the user friendly hints, first, we think of declaring a method.

function ShowMessage () {
    var message = ' Welcome ';
    alert (message);
}

Later, we found that this method only need to execute once, so we remove the method, directly in the JS write:

var message = "Welcome";
alert (message);

At this point we found that if we wanted to declare another message in our future code, we would have to consider the problem of having a message in front of it, so we could write it as a function with the following code:

(function () {
    var message = "Welcome";
    alert (message);
}) ();

This is done only once and isolating the scope.

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.