Javascript匿名函数的立即执行函数避免全局变量之间的污染,语法形式为:
(function() {执行语句})();
或者
(function() {执行语句}());
注意:多个立即执行函数之间要用分号(;)隔开,否则会报错。
示例:第一种写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
(function () {
console.log(11)
})();
</script>
</body>
</html>
一保存上面的代码,就立即执行,控制台输出:
示例:连续写两个立即执行函数,要注意加分号
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
(function () {
let num = 10
console.log(num)
})();
(function () {
let num = 20
console.log(num)
})();
</script>
</body>
</html>
控制台输出:
示例:带参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
(function (x, y) {
console.log(x + y)
})(1, 2);
</script>
</body>
</html>
控制台输出:
示例:第二种写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
(function (x, y) {
console.log(x + y)
}(1, 3));
</script>
</body>
</html>
控制台输出: