Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the use of (function(){xxx})() in js

php中世界最好的语言
Release: 2018-06-04 17:35:48
Original
3049 people have browsed it

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: 14px;'>(function () { /* code */ } ()); <br>!function () { /* code */ } ();<br>~function () { /* code */ } ();<br>-function () { /* code */ } ();<br>+function () { /* code */ } ();</span>
Copy after login
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: 14px;'>!function(){alert('iifksp')}()        // true</span>
Copy after login
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: 14px;'>(function(){alert('iifksp')})()        // true</span>
Copy after login
Or:

<span style='font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;'>(function(){alert('iifksp')}())        // true</span>
Copy after login
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: 14px;'>function a(){alert('iifksp')}        // undefined</span>
Copy after login

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

<span style='font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;'>function a(){alert('iifksp')}()        // SyntaxError: unexpected_token</span>
Copy after login

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

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

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

<span style='font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;'>var i = function(){return 10}();        // undefined  1 && function(){return true}();        // true  1, function(){alert('iifksp')}();        // undefined</span>
Copy after login

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

<span style='font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;'>!function(){alert('iifksp')}()        // true+function(){alert('iifksp')}()        // NaN-function(){alert('iifksp')}()        // NaN~function(){alert('iifksp')}()        // -1</span>
Copy after login

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

<span style='font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;'>void function(){alert('iifksp')}()        // undefined  new function(){alert('iifksp')}()        // Object  delete function(){alert('iifksp')}()        // true</span>
Copy after login

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

<span style='font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;'>(function(){alert('iifksp')})()        // undefined(function(){alert('iifksp')}())        // undefined</span>
Copy after login

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

最后讨论下性能。我在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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!