您的位置:首页 > Web前端

深入理解闭包系列第三篇——IIFE

2016-08-03 07:48 295 查看
×
目录
[1]实现 [2]用途

前面的话

  严格来讲,IIFE并不是闭包,因为它并不满足函数成为闭包的三个条件。但一般地,人们认为IIFE就是闭包,毕竟闭包有多个定义。本文将详细介绍IIFE的实现和用途

实现

  函数跟随一对圆括号()表示函数调用

//函数声明语句写法
function test(){};
test();

//函数表达式写法
var test = function(){};
test();


  但有时需要在定义函数之后,立即调用该函数。这种函数就叫做立即执行函数,全称为立即调用的函数表达式IIFE(Imdiately Invoked Function Expression)

  [注意]javascript引擎规定,如果function关键字出现在行首,一律解释成函数声明语句

  【1】函数声明语句需要一个函数名,由于没有函数名,所以报错

//SyntaxError: Unexpected token (
function(){}();


  【2】函数声明语句后面加上一对圆括号,只是函数声明语句与分组操作符的组合而已。由于分组操作符不能为空,所以报错

//SyntaxError: Unexpected token )
function foo(){}();

//等价于
function foo(){};
();//SyntaxError: Unexpected token )


  【3】函数声明语句加上一对有值的圆括号,也仅仅是函数声明语句与不报错的分组操作符的组合而已

function foo(){}(1);

//等价于
function foo(){};
(1);


  所以,解决方法就是不要让function出现在行首,让引擎将其理解成一个表达式

最常用的两种办法

(function(){ /* code */ }());
(function(){ /* code */ })();


其他写法

var i = function(){ return 10; }();
true && function(){ /* code */ }();
0, function(){ /* code */ }();

!function(){ /* code */ }();
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();

new function(){ /* code */ };
new function(){ /* code */ }();


用途

  IIFE一般用于构造私有变量,避免全局空间污染

  接下来用一个需求实现来更直观地说明IIFE的用途。假设有一个需求,每次调用函数,都返回加1的一个数字(数字初始值为0)

【1】全局变量

  一般情况下,我们会使用全局变量来保存该数字状态

var a = 0;
function add(){
return ++a;
}
console.log(add());//1
console.log(add());//2


【2】自定义属性

  但上面的方法中,变量a实际上只和add函数相关,却声明为全局变量,不太合适。

  将变量a更改为函数的自定义属性更为恰当

function add(){
return ++add.count;
}
add.count = 0;
console.log(add());//1
console.log(add());//2


【3】IIFE

  其实这样做,还是有问题。有些代码可能会无意中将add.count重置

  使用IIFE把计数器变量保存为私有变量更安全,同时也可以减少对全局空间的污染

var add = (function(){
var counter = 0;
return function(){
return ++counter;
}
})();
console.log(add())//1
console.log(add())//2


// var all = document.getElementById('cnblogs_post_body').children;
var select = [];

for(var i = 1; i < all.length; i++){
if(all[i].getAttribute('id')){
if(all[i].getAttribute('id').match(/anchor\d+$/)){
select.push(all[i]);
}
}

}
var wheel = function(e){
e = e || event;
var data;
if(e.wheelDelta){
data = e.wheelDelta;
}else{
data = -e.detail * 40;
}
for(var i = 0; i < select.length; i++){
if(select[i].getBoundingClientRect().top > 0){
return;
}
if(select[i].getBoundingClientRect().top <= 0 && select[i+1]){
if(select[i+1].getBoundingClientRect().top > 0){
change(oCon.children[i+2])
}
}else{
change(oCon.children[select.length+1])
}
}

}
document.body.onmousewheel = wheel;
document.body.addEventListener('DOMMouseScroll',wheel,false);

var oCon = document.getElementById("content");
var close = oCon.getElementsByTagName('span')[0];
close.onclick = function(){
if(this.innerHTML == '显示目录'){
this.innerHTML = '×';
this.style.background = '';
oCon.style.border = '2px solid #ccc';
oCon.style.width = '';
oCon.style.height = '';
oCon.style.overflow = '';
oCon.style.lineHeight = '30px';
}else{
this.innerHTML = '显示目录';
this.style.background = '#3399ff';
oCon.style.border = 'none';
oCon.style.width = '60px';
oCon.style.height = '30px';
oCon.style.overflow = 'hidden';
oCon.style.lineHeight = '';
}
}
for(var i = 2; i < oCon.children.length; i++){
oCon.children[i].onmouseover = function(){
this.style.color = '#3399ff';
}
oCon.children[i].onmouseout = function(){
this.style.color = 'inherit';
if(this.mark){
this.style.color = '#3399ff';
}

}
oCon.children[i].onclick = function(){
change(this);
}
}

function change(_this){
for(var i = 2; i < oCon.children.length; i++){
oCon.children[i].mark = false;
oCon.children[i].style.color = 'inherit';
oCon.children[i].style.textDecoration = 'none';
oCon.children[i].style.borderColor = 'transparent';
}
_this.mark = true;
_this.style.color = '#3399ff';
_this.style.textDecoration = 'underline';
_this.style.borderColor = '#2175bc';
}
// ]]>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐