[转]Javascript中的自执行函数表达式

[转]Javascript中的自执行函数表达式

本文转载自:http://www.ghugo.com/javascript-auto-run-function/

以下是正文:

在写插件或我们日常代码中,经常都会用到自执行函数表达式,最简单,最常用的也就是匿名函数自运行了。
如下代码结构:

 1 (function(){
 2     //code
 3 })()

 

网上看到一篇关于这方面的文章,讲得蛮详细,特转载到博客记录一下。

转载地址:http://suqing.iteye.com/blog/1981591

============================================
在Bootstrap源码(具体请看《Bootstrap源码解析》)和其他jQuery插件经常看到如下的写法:

1 1 +function ($) {  
2 2    
3 3 }(window.jQuery);

这种写法称为:
IIFE (Imdiately Invoked Function Expression 立即执行的函数表达式)。

一步步来分析这段代码。

先弄清 函数表达式(function expression)和 函数声明(function declaration)的区别:
函数表达式 Function Expression – var test = function() {};
函数申明 Function Declaration – function test() {};

函数表达式中的函数可以为匿名函数,也可以有函数名,但是该函数实际上不能直接使用,只能通过表达式左边的变量 a 来调用。

1 1 var a = function(){ 
2 2   alert('Function expression'); 
3 3 } 
4 4 var b = new a(); 

函数声明时必须有函数名。

1 function a(){ 
2   alert('Function declaration'); 
3 } 
4 a(); 

这是一个匿名函数。

1 function () { 
2    
3 } 

你也许注意到匿名函数在console下会报错。console的执行和报错如下:

function(){}

SyntaxError: Unexpected token (

通过一元操作符+变成了函数表达式。也可以使用 – ~ !等其他一元运算符或者括号,目的是为了引导解析器,指明运算符附近是一个表达式。以下是三种经典方式 :

 1 +function () {  
 2    
 3 }; 
 4    
 5 (function () { 
 6    
 7 }); 
 8    
 9 void function() { 
10    
11 }; 

函数表达式通过 末尾的() 来调用并运行。就是一个IIFE。

1 +function () {  
2    
3 }(); 
4    
5 (funtion () { 
6    
7 })(); 

代码性能
运算符:+加-减!逻辑非~位取反,返回NaN(Not A Number)。

“()”组运算符:返回表达式的执行结果undefined。

void:按运算符结合语句执行,返回 undefined。
这几种的性能对比结果:

可见+性能最差(在Firefox下差距更明显),其他几种都差不多。不过IIFE只执行一遍,对js执行效率的影响特别小,使用哪种还是看个人爱好。

传参,为了避免$与其他库或者模板申明冲突,window.jQuery 作为参数传递。

1 +function (x) { 
2     console.log(x); 
3 }(3); 
4    
5 +function ($) { 
6    
7 }(window.jQuery); 

使用IIFE的好处

总结有4点:提升性能、有利于压缩、避免冲突、依赖加载

1、减少作用域查找。使用IIFE的一个微小的性能优势是通过匿名函数的参数传递常用全局对象window、document、jQuery,在作用域内引用这些全局对象。JavaScript解释器首先在作用域内查找属性,然后一直沿着链向上查找,直到全局范围。将全局对象放在IIFE作用域内提升js解释器的查找速度和性能。

传递全局对象到IIFE的一段代码示例:

1 // Anonymous function that has three arguments 
2 function(window, document, $) { 
3    
4   // You can now reference the window, document, and jQuery objects in a local scope 
5    
6 }(window, document, window.jQuery); // The global window, document, and jQuery objects are passed into the anonymous function 

2、有利于压缩。另一个微小的优势是有利于代码压缩。既然通过参数传递了这些全局对象,压缩的时候可以将这些全局对象匿名为一个字符的变量名(只要这个字符没有被其他变量使用过)。如果上面的代码压缩后会变成这样:

1 // Anonymous function that has three arguments 
2 function(w, d, $) { 
3    
4   // You can now reference the window, document, and jQuery objects in a local scope 
5    
6 }(window, document, window.jQuery); // The global window, document, and jQuery objects are passed into the anonymous function 

 

3、避免全局命名冲突。当使用jQuery的时候,全局的window.jQuery对象 作为一个参数传递给$,在匿名函数内部你再也不需要担心$和其他库或者模板申明冲突。 正如James padolsey所说:
An IIFE protects a module’s scope from the environment in which it is placed.

4、通过传参的方式,可以灵活的加载第三方插件。(当然使用模块化加载更好,这里不考虑。)举个例子,如果a页面需要使用KindEditor,a.html引入kindeditor.js 和 a.js
你可能会这么写 a.js:

 1 $(function() { 
 2    
 3    var editor 
 4     KindEditor.ready(function(K) { 
 5    
 6         editor = K.create('textarea[data-name="kindeditor"]', { 
 7             resizeType : 1 
 8         }) 
 9     }) 
10    
11 }) 

b页面不需要使用Kindeditor,没有引入kindeditor.js。但是在合并JS代码后,b页面也会执行a.js中的代码,页面报错Uncaught ReferenceError: KindEditor is not defined。也就是b页面执行了KindEditor,难道所有页面都要加载Kindeditor源文件?
可以这么修改a.js,将KindEditor变量参数化,通过给立即执行的函数表示式的参数赋值,那么其他页面都不需要加载Kindeditor源文件

 1 +function( KindEditor){ 
 2    
 3     var editor 
 4     if(KindEditor){ 
 5         KindEditor.ready(function(K) { 
 6    
 7             editor = K.create('textarea[data-name="kindeditor"]', { 
 8             resizeType : 1 
 9             }) 
10         }) 
11     } 
12    
13 }(KindEditor || undefined) 

IIFE最佳实践
反对使用IIFE的其中一个理由是可读性差,如果你有大量的JavaScript代码都在一段IIFE里,要是想查找IIFE传递的实际参数值,必须要滚动到代码最后。幸运的是,你可以使用一个更可读的模式:

 1 (function (library) { 
 2    
 3     // Calls the second IIFE and locally passes in the global jQuery, window, and document objects 
 4     library(window, document, window.jQuery); 
 5    
 6 } 
 7    
 8 // Locally scoped parameters  
 9 (function (window, document, $) { 
10    
11 // Library code goes here 
12    
13 })); 

这种IIFE模式清晰的展示了传递了哪些全局对象到你的IIFE中,不需要滚动到长文档的最后。

jQuery优化
一段看上去写法有点像的代码。大部分项目用这段代码做作用域,这段代码会在DOM加载完成时初始化jQuery代码。

1 $(function(){  
2    
3 });

这种写法等同于

1 $(document).ready(function(){ 
2 // 在DOM加载完成时初始化jQuery代码。 
3 }); 

区别于

1 $(window).load(function(){ 
2 // 在图片等媒体文件加载完成时,初始化jQuery代码。 
3 }); 

结合IIFE的最佳实践,更好的写法是,立即执行document ready

1 +function ($) { 
2    
3   $(function(){ 
4    
5   }) 
6    
7 }(window.jQuery)

最佳实践

 1 // IIFE - Immediately Invoked Function Expression 
 2   +function(yourcode) { 
 3    
 4     // The global jQuery object is passed as a parameter 
 5     yourcode(window.jQuery, window, document); 
 6    
 7   }(function($, window, document) { 
 8    
 9     // The $ is now locally scoped  
10    
11    // Listen for the jQuery ready event on the document 
12    $(function() { 
13    
14      // The DOM is ready! 
15    
16    })); 

具体请看工程师,请优化你的代码

其他
在Bootstrap和其他插件中经常看到如下写法:

1 +function ($) { "use strict";   
2      
3 }(window.jQuery); 

关于字符串”use strict”;请看严格模式

参考资料:
《Javascript高级程序设计(第3版)》 7.3 模仿块级作用域
Immediately-Invoked Function Expression (IIFE) – Ben Alman
ECMA-262-3 in detail. Chapter 5. Functions. – Dmitry A. Soshnikov
Functions and function scope – Mozilla Developer Network
Named function expressions – Juriy “kangax” Zaytsev
JavaScript Module Pattern: In-Depth – Ben Cherry
Closures explained with JavaScript – Nick Morga
what does function function window jquery do – Stackoverflow
http://gregfranko.com/blog/i-love-my-iife/

posted @ 2016-04-21 13:50  xingba-coder  阅读(401)  评论(0编辑  收藏  举报