封闭函数
封闭函数是javascript中匿名函数的另外一种写法,创建一个一开始就执行而不用命名的函数。
一般定义的函数和执行函数:
function myalert(){
alert('hello!');
};
myalert();
封闭函数:
(function myalert(){
alert('hello!');
})();
还可以在函数定义前加上 “~”或 “!” 等符号来定义匿名函数
!function myalert(){
alert('hello!');
}();
封闭函数的好处
封闭函数可以创造一个独立的空间,在封闭函数内定义的变量和函数不会影响外部同名的函数和变量,可以避免命名冲突,在页面上引入多个js文件时,用这种方式添加js文件比较安全,比如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript">
/*
function myalert(){
alert('hello world!');
}
myalert();
转换成封闭函数的写法:
*/
/*(function(){
alert('hello world!');
})();*/
//封闭函数的第二种写法:
/*!function(){
alert('hello world!');
}();*/
~function(){
alert('hello world!');
}();
var iNum01 = 12;
function myalert02(){
alert('hello world!');
}
// 在封闭函数前加一个“;” , 可以避免js压缩时候出错。
(function(){
var iNum01 = 24;
function myalert02(){
alert('hello hello!');
}
alert(iNum01);
myalert02();
})();
alert(iNum01);
myalert02();
</script>
</head>
<body>
</body>
</html>