Detailed examples of immediate execution of functions in JavaScript
js Immediate execution function allows your function to be executed immediately after creation. The js immediate execution function mode is a syntax that allows your function to be executed immediately after definition. This mode is essentially a function expression ( named or anonymous), executed immediately after creation. Compared with other programming languages, JavaScript is relatively casual, so the JavaScript code is full of all kinds of weird writing methods, which sometimes appear in the fog. Of course, being able to understand various writing methods is also a further in-depth understanding of the characteristics of the JavaScript language. This article mainly introduces you to the relevant information about the immediate execution of functions in JavaScript. Friends in need can refer to it.
Preface
(function(){…})() and (function (){…} ()) are two common ways of writing JavaScript functions to execute functions immediately. At first, I thought they were one Wrap the anonymous function in parentheses, then add a parentheses at the end to call the function, and finally achieve the purpose of executing the function immediately after it is defined. Later, it was discovered that the reason for adding the parentheses was not this.
Not much to say below, let’s take a look at the detailed introduction.
Usually we declare a function in the following ways:
// 声明函数f1 function f1() { console.log("f1"); } // 通过()来调用此函数 f1(); //一个匿名函数的函数表达式,被赋值给变量f2: var f2 = function() { console.log("f2"); } //通过()来调用此函数 f2(); //一个命名为f3的函数的函数表达式(这里的函数名可以随意命名,可以不必和变量f3重名),被赋值给变量f3: var f3 = function f3() { console.log("f3"); } //通过()来调用此函数 f3();
If you have seen some custom controls, you will find that most of them follow this writing method:
(function() { " // 这里开始写功能需求 })();
This is what we often call an immediate execution function (IIFE). As the name suggests, it means that this function executes the function body immediately and does not require you to actively call it. Generally, we only use IIFE for anonymous functions. , this has two purposes:
First, there is no need to name the function, which avoids contaminating global variables
Second, a separate scope is formed inside IIFE, which can encapsulate some Private variables not readable by outsiders.
If you can’t understand these two sentences, let’s start with the operating principle of IIFE.
Because IIFE is usually used for anonymous functions, here we use a simple anonymous function as an example:
var f = function(){ console.log("f"); } f();
We find that f here is just a reference variable of this anonymous function, then since f () can call this function. Can I replace f with the function itself:
function(){ console.log("f"); }();
After running, I get the following results:
Uncaught SyntaxError: Unexpected token (
The reason for this error is that the Javascript engine sees the function key After the word, it is considered that what follows is a function declaration statement and should not end with parentheses. The solution is to let the engine know that the part before the parentheses is not a function definition statement, but an expression, which can be operated on. Here is a distinction between function declaration and function expression:
1. Function declaration ( That is, we usually use function x(){} to declare a function)
function myFunction () { /* logic here */ }
2. Function expression (similar to this form)
var myFunction = function () { /* logic here */ }; var myObj = { myFunction: function () { /* logic here */ } };
Primary school we I have learned that expressions enclosed with () will be executed first, like the following:
1+(2+3) //这里先运行小括号里面的内容没有意见撒
In fact, parentheses also have a similar effect in JavaScript. When the Javascript engine sees the function keyword, it will think it is a function declaration statement. So what happens if the Javascript engine sees the parentheses first:
//用小括号把函数包裹起来 (function(){ console.log("f"); })();
The function is successfully executed:
f //控制台输出
In this case, the Javascript engine will think that this is an expression, not a function Statement, of course there are many ways to make the Javascript engine think that this is an expression:
!function(){}(); +function(){}(); -function(){}(); ~function(){}(); new function(){ /* code */ } new function(){ /* code */ }() // 只有传递参数时,才需要最后那个圆括号。 ……
Back to the previous question, why is it said that the form of IIFE avoids polluting global variables? If you have seen others write The jquery plug-in usually has code similar to this:
(function($){ " //插件实现代码 })(jQuery);
The jquery here is actually the parameter of the anonymous function. Think about it when we call the anonymous function, we use f(), then the anonymous parameter is f (args) Right, here jquery is passed into the function as a parameter, then when the formal parameter $ is used inside the function, it will not affect the external environment, because some plug-ins also use the $ qualifier. The interior can be modified as desired.
Above, I referred to the following two articles during this process:
javascript executes a function immediately: think about function(){}() in the plug-in
Immediate execution function in JavaScript
Related recommendations:
Add operator before analysis function to implement immediate execution function
JavaScript anonymous, named function and immediate execution function IIFE detailed explanation
Immediate execution function in JS
The above is the detailed content of Detailed examples of immediate execution of functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
