介绍IIFE

  • IIFE的性能
  • 使用IIFE的好处
  • IIFE最佳实践
  • jQuery优化

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

+function ($) {   

}(window.jQuery);  

这种写法称为:

IIFE (Imdiately Invoked Function Expression 立即执行的函数表达式)。

来分析这段代码

先弄清函数表达式(function expression)和 函数声明(function declaration)的区别:

函数表达式  Function Expression

 var test = function() {}; 

函数申明     Function Declaration

function test() {}

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

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

function a(){
alert('Function declaration');
}
a();

这是一个匿名函数

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

function(){}

 
SyntaxError: Unexpected token (

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

+function () {   

};  

(function () {  

});  

void function() {  

};  

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

+function () {   

}();  

(funtion () {  

})();  

代码性能

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

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

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

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

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

+function (x) {
console.log(x);
}(3); +function ($) { }(window.jQuery);

使用IIFE的好处

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

1、减少作用域查找。使用IIFE的一个微小的性能优势是通过匿名函数的参数传递常用全局对象window、document、jQuery,在作用域内引用这些全局对象。

JavaScript解释器首先在作用域内查找属性,然后一直沿着链向上查找,直到全局范围。将全局对象放在IIFE作用域内提升js解释器的查找速度和性能。

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

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

2、有利于压缩。另一个微小的优势是有利于代码压缩。既然通过参数传递了这些全局对象,压缩的时候可以将这些全局对象匿名为一个字符的变量名(只要

这个字符没有被其他变量使用过)。如果上面的代码压缩后会变成这样:

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:

$(function() {  

   var editor
KindEditor.ready(function(K) { editor = K.create('textarea[data-name="kindeditor"]', {
resizeType : 1
})
}) })

b页面不需要使用Kindeditor,没有引入kindeditor.js。但是在合并JS代码后,b页面也会执行a.js中的代码,页面报错Uncaught ReferenceError: KindEditor is not defined。

也就是b页面执行了KindEditor,难道所有页面都要加载Kindeditor源文件?

可以这么修改a.js,将KindEditor变量参数化,通过给立即执行的函数表示式的参数赋值,那么其他页面都不需要加载Kindeditor源文件

+function( KindEditor){  

    var editor
if(KindEditor){
KindEditor.ready(function(K) { editor = K.create('textarea[data-name="kindeditor"]', {
resizeType : 1
})
})
} }(KindEditor || undefined)

IIFE最佳实践

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

可以使用一个更可读的模式:

(function (library) {  

    // Calls the second IIFE and locally passes in the global jQuery, window, and document objects
library(window, document, window.jQuery); } // Locally scoped parameters
(function (window, document, $) { // Library code goes here }));

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

jQuery优化

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

$(function(){   

}); 

这种写法等同于

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

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

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

+function ($) {  

  $(function(){  

  })  

}(window.jQuery)  
+function(yourcode) {  

// The global jQuery object is passed as a parameter
yourcode(window.jQuery, window, document); }(function($, window, document) { // The $ is now locally scoped // Listen for the jQuery ready event on the document
$(function() { // The DOM is ready! }) });

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

其他

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

+function ($) { "use strict";    

}(window.jQuery);  

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

延伸阅读:Bootstrap源码解析

参考资料:

《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/

【注:】转载http://suqing.iteye.com/blog/1981591

最新文章

  1. 将Centos的yum源更换为国内的阿里云源
  2. import com.sun.image.codec.jpeg.JPEGCodec不通过 找不到包
  3. [Xamarin] 簡單使用AlertDialog (转帖)
  4. 解决CSS移动端1px边框问题
  5. Asp.net Session保存到Redis: 使用 RedisSessionStateProvider
  6. 【题解】【排列组合】【回溯】【Leetcode】Generate Parentheses
  7. RPi 2B apache2 mysql php5 and vsftp
  8. NewtonSoft.json 序列化和反序列化实例
  9. [python]类与类中的列表
  10. 【WPF】三维模型中的“照相机”
  11. Android中的intent属性
  12. ACE在windows下的编译及配置(VS2010)
  13. 解决SQL Server 2008无法连接127.0.0.1的问题
  14. json处理+list.sort()排序
  15. DRF 序列化组件
  16. strut2 的数据验证
  17. IDEA使用SpringBoot 、maven创建微服务的简单过程
  18. MapServer和GeoServer对比
  19. 1019C Sergey's problem(思维)
  20. HTML5 Canvas ( 图形的阴影 ) shadowColor, shadowOffsetX, shadowOffsetY, shadowNlur

热门文章

  1. 运行scrapy保存图片,报错ValueError: Missing scheme in request url: h
  2. 通过profile优化SQL语句
  3. 并发 错误 java.lang.IllegalMonitorStateException: current thread not owner 分析
  4. LeetCode:二叉树的锯齿形层次遍历【103】
  5. maven 项目打包时无法解析读取properties文件
  6. iOS 关于自动更新的分阶段发布(灰度发布)的相关简介
  7. 转:MFC中屏蔽ESC和回车关闭对话框
  8. jQuery UI入门
  9. 【LeetCode】【定制版排序】Sort Colors
  10. ubuntu 12.04.2 基于 L3.0.35_1.1.0_121218_source LTIB 问题汇总