JavaScript Basics: Immediate Execution Function

JavaScript Basics: Immediate Execution Function

Sometimes you see some amazing functions in JavaScript, such as the following screenshot:

insert image description here

This kind of function will run automatically as long as the browser is loaded and needs to be called. This kind of function was also mentioned in the closure before. It is generally called: immediately executed function.

Characteristics of immediate functions:

  • Will automatically execute
  • Will only be executed once

Immediately execute function format

The immediate execution function generally has the following format:

# Format 1 (//W3C recommends this format)
(function (){
 }())
 
#Format 2 (but this is one of the most commonly used methods)
(function (){
 })();
 

In fact, we can also see from the above that when executing functions immediately, the function name is generally not written, which is not very meaningful. After all, the immediate function does not need to be called through the function name. This is similar to the effect when defining a function literally.

Now let's take an example combining closures and immediately executed functions:

var fun = (
function(){
  function test(a,b){
      console.log(a+b);
  }    
  return test;
}
)()
 

insert image description here

Other ways to execute functions immediately – expressions

The above immediately executed function format definition, but there are other ways to implement this function, such as the following is not the above format

!function(){
    console.log("test");
}()

insert image description here

We can see the two lines of output. The first one is test, which is the result of executing the function immediately, and true is output because there is an extra one in front! , this was mentioned during implicit conversion, in! The following will force a line break Boolean type.

Now there is another question, why can this method be implemented?

To analyze how this happens, let's first look at an expression function:

var test = function(){
    console.log("test expression")
}
#After this declaration, how to use it? As follows test();
 

insert image description here

At this time, a bold idea came to my mind. The assigned function can be executed by adding variable value to (), so why can't it be written directly?

var test = function(){
    console.log("test expression")
}()

insert image description here

Here we can see that the expression function also has an immediate execution effect.

(Additional information: Why is there undefined? Because this function itself has no return value, so the value undefined is output in the browser console panel.)

Is it okay to put parentheses directly after the function?

function(){
    console.log("test expression")
}()

insert image description here

It can be seen that you need to use the expression premise before you can put () at the end, otherwise an error will be reported.

At this time, I had a bold idea, actually! The following method actually converts the function into an expression function, so the subsequent + () can be run directly. Then I have a bold idea. In this case, let’s just add a plus sign (+) before the function and try it.

+function(){
    console.log("test expression")
}()
 

insert image description here

Since the plus sign can then:

+ -
! ~

Of course, the so-called multiplication and division signs cannot be realized. There is another magical keyword that can also have this magical effect, that is, new and void.

new function(){
    console.log("test expression")
}()

insert image description here

Another thing is that the logical operators || and && can also be used to implement

However, this needs to be preceded by true or false according to its characteristics, and it cannot be used alone.

1 && function(){
    console.log("test expression")
}()
 or 0 || function(){
    console.log("test expression")
}()
 

insert image description here

There is also a magic symbol (comma) that can achieve this function:

1,function(){
    console.log("test expression")
}()
 

insert image description here

It can be seen that if a comma is used, the following expression function will be executed regardless of whether the previous one is true or false.

Immediately executed functions can take parameters

Immediately executed functions can also have parameters, as follows

(function(a,b){
    console.log(a,b)
})(1,2)
 

insert image description here

application

This question is a classic interview question. First, create the next html

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>test</title> 
</head>
<body>
<ul id=”test”>
    <li>This is the first one</li>
     <li>This is the second one</li>
    <li>This is the third one</li>
 </ul>
<script>
  var liList = document.getElementsByTagName('li');
     for(var i=0;i<liList.length;i++)
     {
         liList[i].onclick=function(){
             console.log(i);
         }
     };
</script>
 </body>
</html>

The purpose is to click on the number of labels li output a number, but the result

insert image description here

Because the for loop has already completed when li is clicked, this can be solved by using the let keyword learned earlier.

  var liList = document.getElementsByTagName('li');
     for(let i=0;i<liList.length;i++)
     {
         liList[i].onclick=function(){
             console.log(i);
         }
     };

insert image description here

This can solve the problem, but it does not use the immediate function. Of course, it can also be modified by executing the function immediately.

 var liList = document.getElementsByTagName('li');
     for(let i=0;i<liList.length;i++)
     { (function(a){
        liList[a].onclick=function(){
             console.log(a);
         } 
      })(i)
      };

insert image description here

It can be seen that the immediately executed function will form its own closed space, which will not be affected by other external variables. In fact, if there is a return, it is a standard closure.

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Analysis of usage of anonymous functions executed immediately in JS
  • Analysis of JS immediate execution function function and usage
  • Detailed explanation of examples of immediately executing functions in JavaScript
  • Detailed explanation of immediately executed functions in JS
  • JavaScript immediate execution function usage analysis

<<:  Detailed explanation of how to modify the style of el-select: popper-append-to-body and popper-class

>>:  Flash embedded in HTML Solution for embedding Flash files in HTML web page code (Part 2)

Recommend

Several popular website navigation directions in the future

<br />This is not only an era of information...

Steps to run ASP.NET Core in Docker container

There are too much knowledge to learn recently, a...

Detailed discussion on the issue of mysqldump data export

1. An error (1064) is reported when using mysqldu...

Windows Server 2016 Standard Key activation key serial number

I would like to share the Windows Server 2016 act...

Analysis of two usages of the a tag in HTML post request

Two examples of the use of the a tag in HTML post...

Let you understand the working principle of JavaScript

Table of contents Browser kernel JavaScript Engin...

4 principles for clean and beautiful web design

This article will discuss these 4 principles as t...

Implementation of CSS equal division of parent container (perfect thirds)

The width of the parent container is fixed. In or...

Nofollow makes the links in comments and messages really work

Comments and messages were originally a great way...

CSS3 implements the sample code of NES game console

Achieve resultsImplementation Code html <input...

Docker Compose network settings explained

Basic Concepts By default, Compose creates a netw...

mysql show simple operation example

This article describes the mysql show operation w...

jQuery combined with CSS to achieve the return to top function

CSS Operations CSS $("").css(name|pro|[...