Detailed answer to immediate execution function in JavaScript
The immediate execution function mode in JavaScript allows your function to be executed immediately after being defined. Let’s deeply analyze the immediate execution function in JavaScript. Friends who need it can refer to it
What is itIn JavaScript, every function, when called, creates a new execution context. Because variables defined within functions and functions are the only variables that are accessed internally, rather than externally, the context provided by the function provides a very simple way to create private variables when the function is called.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
In many cases, you may not need a function like makeWhatever to return multiple accumulated values, and can only call it once to get a single value. In other cases, you do not even need to explicitly Know the return value.
The core of itNow, whether you define a function like this function foo(){} or var foo = function(){}, when calling, you need to add A pair of parentheses, like foo().
1 2 3 4 5 6 7 8 |
|
As you can see, an error was caught here. When parentheses appear after a function for calling a function, whether it encounters such a function keyword in the global environment or the local environment, by default, it will treat it as a function declaration rather than a function expression. If you If you don't explicitly tell the parentheses that it is an expression, it will treat it as a function declaration without a name and throw an error, since function declarations require a name.
Question 1: Can we think about a question here, can we also directly call the function like this var foo = function(){console.log(1)}(), the answer is yes.
Question 2: Similarly, we can also think about a question. If a function declaration like this is directly called with parentheses at the end, what will happen? Please see the answer below.
Functions, parentheses, errorsInterestingly, if you specify a name for a function and put a pair of parentheses after it, the same error will be thrown, but this This time it was for another reason. When parentheses are placed after a function expression, it indicates that this is a called function, and when parentheses are placed after a declaration, it means that it is completely separated from the previous function declaration. At this time, the parentheses are just a simple representation. A parentheses (parentheses used to control the precedence of operations).
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Immediately executed function expression (IIFE) Fortunately, fixing syntax errors is easy. The most popular and accepted method is to wrap a function declaration in parentheses to tell the parser to express a function expression, because in JavaScript, parentheses cannot contain declarations. Because of this, when parentheses enclose a function and encounter the function keyword, it knows to parse it as a function expression rather than a function declaration. Note that the parentheses here behave differently than the parentheses above when they encounter functions, that is to say.
When parentheses appear at the end of an anonymous function and you want to call the function, it will default to the function as a function declaration.
When parentheses wrap a function, it will default to parsing the function as an expression instead of a function declaration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
Important notes about parenthesesIn some cases, additional ambiguous parentheses around a function expression are not necessary (because the parentheses at this time have already separated it. as an expression), but it's still a good idea when parentheses are used to call function expressions.
Such brackets indicate that the function expression will be called immediately, and the variable will store the result of the function, not the function itself. When this is a very long function expression, this can save a person reading your code time from having to scroll to the bottom of the page to see if the function is called.
As a rule, when you write clear and concise code, it is necessary to prevent JavaScript from throwing errors, and it is also necessary to prevent other developers from throwing errors WTFError!
Preserving the state of a closure Just as arguments are passed when a function is called by their name, arguments are also passed when a function expression is called immediately. An immediately called function expression can be used to lock the value and effectively save the current state, because any function defined within a function can use the parameters and variables passed in by the outer function (this relationship is called a closure) .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
Remember, in these last two examples, lockedInIndex can access i without any problems, but using a different named identifier as the function parameter can make the concept easier to explain.
One of the most significant advantages of executing a function immediately is that even if it is unnamed or anonymous, a function expression can be called immediately without an identifier, and a closure can be called immediately without a current variable. contamination is used.
What are the problems with self-executing anonymous function ("Self-executing anonymous function")?
你看到它已经被提到好几次了,但是它仍然不是那么清楚的被解释,我提议将术语改成"Immediately-Invoked Function Expression",或者,IIFE,如果你喜欢缩写的话。
什么是Immediately-Invoked Function Expression呢?它使一个被立即调用的函数表达式。就像引导你去调用的函数表达式。
我想Javascript社区的成员应该可以在他们的文章里或者陈述里接受术语,Immediately-Invoked Function Expression和 IIFE,因为我感觉这样更容易让这个概念被理解,并且术语"self-executing anonymous function"真的也不够精确。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
希望上面的例子可以让你更加清楚的知道术语'self-executing'是有一些误导的,因为他并不是执行自己的函数,尽管函数已经被执行。同样的,匿名函数也没用必要特别指出,因为,Immediately Invoked Function Expression,既可以是命名函数也可以匿名函数。
最后:模块模式当我调用函数表达式时,如果我不至少一次的提醒我自己关于模块模式,我便很可能会忽略它。如果你并不属性 JavaScript 里的模块模式,它和我下面的例子很像,但是返回值用对象代替了函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
模块模式方法不仅相当的厉害而且简单。非常少的代码,你可以有效的利用与方法和属性相关的命名,在一个对象里,组织全部的模块代码即最小化了全局变量的污染也创造了使用变量。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
原生JavaScript来实现对dom元素class的操作方法(图文教程)
The above is the detailed content of Detailed answer to immediate execution function in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We
