自执行(自调用)函数可以创建独立的作用域避免全局污染,以及项目中多个js文件中全局变量或方法命名冲突的问题;
用法:(函数)(实参),()中可以传递参数,下面例子是自调用匿名函数,也可以设置函数名;
在其他博客中看到一个例子:
for(var i=0; i<6; i++){
liList[i].onclick = function(){
alert(i) // 为什么 alert 出来的总是 6,而不是 0、1、2、3、4、5
}
}
仔细分析发现该for循环在执行该段js代码当i=6时不符合循环条件结束遍历,为每一个li元素添加了click事件,当点击li元素是触发click事件alert出i的值就是6.
可以使用自调用函数改变作用域,这样点击触发返回的就是0—5.
for(var i=0;i<6;i++){
(function (j) {
list[j].οnclick=function (ev) {
alert(j);
}
})(i)
}
注意:
1、自调用函数中所有变量和方法都是局部作用域内的,想要设置成全局作用域供外部访问,可以在函数体内设置window.fn=fn;
2、当使用多个自调用函数时,需要在自定义函数前面加‘;’分号来避免浏览器解析错误,放置自执行函数开始的()与前面代码结合被看成一个函数而解析错误
例子代码:
;(function () {
var foods=[];//记录食物元素
function Food(options) {
options=options||{};
this.x=options.x||0;
this.y=options.y||0;
this.width=options.width||20;
this.height=options.height||20;
this.backgroundColor=options.backgroundColor||'green';
}
Food.prototype.render=function (map) {
//每次渲染一个新的食物时都要删除之前的食物
remove();
var div=document.createElement('div');
map.appendChild(div);
foods.push(div);
this.x=Tools.getRandom(0,map.offsetWidth/this.width-1)*this.width;
this.y=Tools.getRandom(0,map.offsetHeight/this.height-1)*this.height;
div.style.position='absolute';
div.style.width=this.width+'px';
div.style.height=this.height+'px';
div.style.left=this.x+'px';
div.style.top=this.y+'px';
div.style.backgroundColor=this.backgroundColor;
}
//删除食物的方法
function remove() {
for(var i=foods.length-1;i>=0;i--){
//删除食物节点
foods[i].parentNode.removeChild(foods[i]);
//删除数组中的食物元素
foods.splice(i,1);
}
}
window.Food=Food;
})();
var map=document.querySelector('.container');
var food=new Food();
food.render(map);