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

Alibaba Cloud Server Domain Name Resolution Steps (Tutorial for Beginners)

For novices who have just started to build a webs...

JavaScript to achieve elastic navigation effect

This article shares the specific code for JavaScr...

Vue achieves seamless carousel effect

This article shares the specific code of Vue to a...

Uncommon but useful tags in Xhtml

Xhtml has many tags that are not commonly used but...

JS thoroughly understands GMT and UTC time zones

Table of contents Preface 1. GMT What is GMT Hist...

WebStorm cannot correctly identify the solution of Vue3 combined API

1 Problem Description Vue3's combined API can...

jQuery canvas draws picture verification code example

This article example shares the specific code of ...

Detailed explanation of Linux environment variable configuration strategy

When customizing the installation of software, yo...

Detailed explanation of Linux CPU load and CPU utilization

CPU Load and CPU Utilization Both of these can re...

How to match the size of text in web design: small text, big experience

With the rise of mobile terminals such as iPad, p...

Analysis of MySQL multi-table joint query operation examples

This article describes the MySQL multi-table join...

Detailed explanation of viewing and setting file permissions on Mac

Preface To modify file permissions in the termina...

How to reduce memory usage and CPU usage of web pages

Some web pages may not look large but may be very...

Docker images export and import operations

What if the basic images have been configured bef...