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

This article helps you understand PReact10.5.13 source code

Table of contents render.js part create-context.j...

Introduction to Docker Architecture

Docker includes three basic concepts: Image: A Do...

Vue+swiper realizes timeline effect

This article shares the specific code of vue+swip...

Basic usage and pitfalls of JavaScript array sort() method

Preface In daily code development, there are many...

In-depth explanation of InnoDB locks in MySQL technology

Table of contents Preface 1. What is a lock? 2. L...

25 Examples of Using Circular Elements in Web Design

Today, this post lists some great examples of circ...

How to install Mysql5.7 in Centos6

environment Centos 6.6 MySQL 5.7 Install If the s...

Vue Page Stack Manager Details

Table of contents 2. Tried methods 2.1 keep-alive...

Use iptables and firewalld tools to manage Linux firewall connection rules

Firewall A firewall is a set of rules. When a pac...

Use ab tool to perform API stress test on the server

Table of contents 1 A brief introduction to syste...

Solution to slow response of Tomcat server

1. Analytical thinking 1. Eliminate the machine&#...

Differences and usage examples of for, for...in, for...of and forEach in JS

for loop Basic syntax format: for(initialize vari...

Teach you how to quickly install Nginx in CentOS7

Table of contents 1. Overview 2. Download the Ngi...

8 tips for Vue that you will learn after reading it

1. Always use :key in v-for Using the key attribu...