search
HomeWeb Front-endJS TutorialDetailed explanation of the use of (function(){xxx})() in js

This time I will bring you a detailed explanation of the use of js's (function(){xxx})(), what are the precautions for using js's (function(){xxx})(), as follows This is a practical case, let’s take a look at it.

(function(){xxx})(); writing method analysis in js

##Self-executionAnonymous function

  • ##Common format: (function() { /* code */ })();

  • # #Explanation: The first pair of brackets surrounding the function (function(){}) returns an unnamed function to the script, and then a pair of empty brackets immediately executes the returned unnamed function. Inside the brackets are the parameters of the anonymous
  • function

    .

  • Function: You can use it to create a
  • namespace

    , as long as you write all your code in this special function package, then It cannot be accessed from outside unless you allow it (prefix the variable with window so that the function or variable becomes global). The code of each JavaScript library is basically organized in this way.

  • To summarize, the main functions of the execution function are anonymous and automatic execution. The code is already running when it is interpreted.

Other ways of writing

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>(function () { /* code */ } ()); <br>!function () { /* code */ } ();<br>~function () { /* code */ } ();<br>-function () { /* code */ } ();<br>+function () { /* code */ } ();</span>
function and exclamation mark

I can calm down when I have some time recently Let’s take a look at various codes. The frequent appearance of function and exclamation marks reminds me of the same question raised by @西子剑影 when I returned to Hangzhou 2 months ago for the last team meeting: If you add an exclamation mark before function (!) What will happen? For example, the following code:

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>!function(){alert('iifksp')}()        // true</span>
The value obtained after running on the console is true. Why it is true is easy to understand, because this anonymous function does not return a value, and the default return value is undefined. , the negation result is naturally true. So the question is not about the result value, but why can the negation operation make the self-tuning of an anonymous function legal?

We may be more accustomed to adding parentheses to call anonymous functions:

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>(function(){alert('iifksp')})()        // true</span>
Or:

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>(function(){alert('iifksp')}())        // true</span>
Although the positions of the brackets above are different, the effect is exactly the same.

So, what are the benefits that make many people so fond of this exclamation point method? If it is just to save one character, it is too unnecessary. Even a 100K library may not save much space. Since it is not space, it means that there may be time considerations. The facts are difficult to tell. Performance is mentioned at the end of the article.

Back to the core question, why can this be done? The even more central question is, why is this necessary?

In fact, whether it is parentheses or exclamation points, there is only one thing that the entire statement can legally do, which is to turn a function declaration statement into an expression.

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>function a(){alert('iifksp')}        // undefined</span>

这是一个函数声明,如果在这么一个声明后直接加上括号调用,解析器自然不会理解而报错:

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>function a(){alert('iifksp')}()        // SyntaxError: unexpected_token</span>

因为这样的代码混淆了函数声明和函数调用,以这种方式声明的函数 a,就应该以 a(); 的方式调用。

但是括号则不同,它将一个函数声明转化成了一个表达式,解析器不再以函数声明的方式处理函数a,而是作为一个函数表达式处理,也因此只有在程序执行到函数a时它才能被访问。

所以,任何消除函数声明和函数表达式间歧义的方法,都可以被解析器正确识别。比如:

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>var i = function(){return 10}();        // undefined  1 && function(){return true}();        // true  1, function(){alert('iifksp')}();        // undefined</span>

赋值,逻辑,甚至是逗号,各种操作符都可以告诉解析器,这个不是函数声明,它是个函数表达式。并且,对函数一元运算可以算的上是消除歧义最快的方式,感叹号只是其中之一,如果不在乎返回值,这些一元运算都是有效的:

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>!function(){alert('iifksp')}()        // true+function(){alert('iifksp')}()        // NaN-function(){alert('iifksp')}()        // NaN~function(){alert('iifksp')}()        // -1</span>

甚至下面这些关键字,都能很好的工作:

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>void function(){alert('iifksp')}()        // undefined  new function(){alert('iifksp')}()        // Object  delete function(){alert('iifksp')}()        // true</span>

最后,括号做的事情也是一样的,消除歧义才是它真正的工作,而不是把函数作为一个整体,所以无论括号括在声明上还是把整个函数都括在里面,都是合法的:

<span style="font-family: 微软雅黑, " microsoft yahei font-size:>(function(){alert('iifksp')})()        // undefined(function(){alert('iifksp')}())        // undefined</span>

说了这么多,实则在说的一些都是最为基础的概念——语句,表达式,表达式语句,这些概念如同指针与指针变量一样容易产生混淆。虽然这种混淆对编程无表征影响,但却是一块绊脚石随时可能因为它而头破血流。

最后讨论下性能。我在jsperf上简单建立了一个测试:http://jsperf.com/js-funcion-expression-speed ,可以用不同浏览器访问,运行测试查看结果。我也同时将结果罗列如下表所示(由于我比较穷,测试配置有点丢人不过那也没办法:奔腾双核1.4G,2G内存,win7企业版):

Option Code Ops/sec
Chrome 13 Firefox 6 IE9 Safari 5
! !function(){;}() 3,773,196 10,975,198 572,694 2,810,197
function(){;}() 21,553,847 12,135,960 572,694 1,812,238
- -function(){;}() 21,553,847 12,135,960 572,694 1,864,155
~ ~function(){;}() 3,551,136 3,651,652 572,694 1,876,002
(1) (function(){;})() 3,914,953 12,135,960 572,694 3,025,608
(2) (function(){;}()) 4,075,201 12,135,960 572,694 3,025,608
void void function(){;}() 4,030,756 12,135,960 572,694 3,025,608
new new function(){;}() 619,606 299,100 407,104 816,903
delete delete function(){;}() 4,816,225 12,135,960 572,694 2,693,524
= var i = function(){;}() 4,984,774 12,135,960 565,982 2,602,630
&& 1 && function(){;}() 5,307,200 4,393,486 572,694 2,565,645
|| 0 || function(){;}() 5,000,000 4,406,035 572,694 2,490,128
& 1 & function(){;}() 4,918,209 12,135,960 572,694 1,705,551
| 1 | function(){;}() 4,859,802 12,135,960 572,694 1,612,372
^ 1 ^ function(){;}() 4,654,916 12,135,960 572,694 1,579,778
, 1, function(){;}() 4,878,193 12,135,960 ##572,694 2,281,186

#It can be seen that the results produced by different methods are not the same, and the differences are huge and vary from browser to browser.

But we can still find many commonalities among them: the new method is always the slowest - and of course this is. In many other aspects, the differences are actually not big, but one thing is for sure, the exclamation point is not the most ideal choice. On the other hand, traditional brackets always perform very quickly in tests, and are faster than exclamation marks in most cases - so there is no problem with the method we usually use, and it can even be said to be optimal. The plus and minus signs perform amazingly in Chrome, and are generally fast in other browsers, and they work better than the exclamation mark.

Of course this is just a simple test and cannot explain the problem. But some conclusions make sense: parentheses and plus and minus signs are optimal.

But why do so many developers love exclamation points? I think this is just a matter of habit, and the advantages and disadvantages between them can be completely ignored. Once you get used to a coding style, this convention will transform your program from confusing to readable. If you get used to the exclamation point, I have to admit, it has better readability than parentheses. I don’t have to pay attention to the matching brackets when reading, nor do I accidentally forget when writing-

When I do the same and then shout that this actually saves another character and feel smug. , but forgot the embarrassment and absurdity of hurriedly digging out a rolled-edge C language textbook... Everyone forgets sometimes, and when he picks it up again, what he picked up is not just forgotten. something.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of JS framework library use cases

How to use native js to create a starry sky effect

The above is the detailed content of Detailed explanation of the use of (function(){xxx})() in js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

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.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

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),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use