分享

js中(function(){}()),(function(){})(),$(function(){});之间的区别

 秋水共蓝天 2019-12-25

2018-10-30 11:04:13 

1. (function(){}())与(function(){})()
这两种写法,都是一种立即执行函数的写法,即IIFE (Immediately Invoked Function Expression)。这种函数在函数定义的地方就直接执行了。

通常的函数声明和调用分开的写法如下:

  1. function foo() {/*...*/} // 这是定义,Declaration;定义只是让解释器知道其存在,但是不会运行。
  2. foo(); // 这是语句,Statement;解释器遇到语句是会运行它的。


普通的函数声明function foo(){}是不会执行的。这里如果直接这样写function foo(){}()解释器会报错的,因为是错误的语法。 
IIFE函数的调用方式通常是将函数表达式、它的调用操作符、分组操作符放到一个括号内,来告诉解释器这里有一个需要立即执行的函数。否则通常情况下,解析器遇到一个function关键字,都会把它当做是一个函数声明,而不是函数表达式。 
如下几种写法都是可以的:

  1. (function foo(){/*...*/}());
  2. (function foo(){/*...*/})();
  3. !function foo() {/*...*/}();
  4. +function foo() {/*...*/}();
  5. -function foo() {/*...*/}();
  6. ~function foo() {/*...*/}();


在需要表达式的场景下,就不需要用括号括起来了:

  1. void function(){/*...*/}();
  2. var foo = function(){/*...*/}();
  3. true && function () { /*...*/ }();
  4. 0, function () { /*...*/ }();


void声明了不需要返回值,第二个则将IIFE函数的返回值赋给了foo。第三、第四个都是明确需要表达式的场景,所以解析器会认识这种写法。

对于IIFE函数,也可以给它们传入参数,例如:

(function foo(arg1,arg2,...){...}(param1,param2,...));


对于常见的(function($){...})(jQuery);即是将实参jQuery传入函数function($){},通过形参$接收。 
上述函数中,最开始的那个括号,可能会由于js中自动分号插入机制而引发问题。例如:

  1. a = b + c
  2. ;(function () {
  3. // code
  4. })();


如果没有第二行的分号,那么该处有可能被解析为c()而开始执行。所以有的时候,可能会看到这样的写法:;(function foo(){/*...*/}()),前边的分号可以认为是防御型分号。

2. 第二类是$(function(){});
$(function(){/*...*/});是$(document).ready(function(){/*...*/})的简写形式,是在DOM加载完成后执行的回调函数,并且只会执行一次。

  1. $( document ).ready(function() {
  2. console.log( "ready!" );
  3. });


  1. $(function() {
  2. console.log( "ready!" );
  3. });


起到的效果完全一样。

在一个页面中不同的js中写的$(function(){/*...*/});函数,会根据js的排列顺序依次执行。 
例如: 
test.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head></head>
  4. <body>
  5. <span>This page is shown to understand '$(document).ready()' in jQuery. <br /><span>
  6. <p>
  7. If you see this line, it means DOM hierarchy has been loaded. NOW loading jQuery from server and execute JS...<br /><br />
  8. </p>
  9. <script src="http://code./jquery-latest.js"></script>
  10. <script src="test1.js"></script>
  11. <script src="test2.js"></script>
  12. </body>
  13. </html>

test1.js

  1. $(function(){
  2. $(document.body).append("$(document).ready()1 is now been executed!!!<br /><br />");
  3. });

test2.js

  1. $(function(){
  2. $(document.body).append("$(document).ready()2 is now been executed!!!<br /><br />");
  3. });

最后可以看到页面输出如下:

  1. This page is shown to understand '$(document).ready()' in jQuery.
  2. If you see this line, it means DOM hierarchy has been loaded. NOW loading jQuery from server and execute JS...
  3. $(document).ready()1 is now been executed!!!
  4. $(document).ready()2 is now been executed!!!

原文:https://blog.csdn.net/stpice/article/details/80586444 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多