<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul id=”test”>
<li>这是第一条</li>
<li>这是第二条</li>
<li>这是第三条</li>
</ul>
<script>
//点击任意一个li,结果都是3,为什么?
//因为作用域不同,在触发onclick事件之前,for循环已经执行结束
var liList = document.getElementsByTagName('li');
for (var i = 0; i < liList.length; i++) {
liList[i].onclick = function () {
console.log(i);
}
}
//怎么解决?创造一个独立作用域:1.把var改成let 2.使用立即执行函数
var liList = document.getElementsByTagName('li');
for (var i = 0; i < liList.length; i++) {
(function (i) {
liList[i].onclick = function () {
console.log(i);
}
})(i);
}
// 例子2
/* for (var k = 0; k < 10; k++) {
setTimeout(function () {
console.log(k);//10个10
}, 0);
}*/
</script>
<script>
console.log('====================无参匿名立即执行函数写法(8种)======================================');
+function () {
console.log('+')
}();
-function () {
console.log('-')
}();
~function () {
console.log('~')
}();
!function () {
console.log('!')
}();
(function () {
console.log('()在外面')
})();
(function () {
console.log('()在里面')
}());
void function () {
console.log('void')
}();
new function () {
console.log('new')
}();
console.log('====================有参匿名立即执行函数写法(7种)======================================');
console.log(
+function (x, y) {
return x + y;
}(2, 3)//5
);
console.log(
-function (x, y) {
return x + y;
}(2, 3)//-5
);
console.log(
~function (x, y) {
return x + y;
}(2, 3)//-6(-5-1)
);
console.log(
!function (x, y) {
return x + y;
}(3, 3)//false
);
console.log(
(function (x, y) {
return x + y;
})(2, 3)//5
);
console.log(
(function (x, y) {
return x + y;
}(2, 3))//5
);
console.log(
function (x, y) {
return x + y;
}(2, 3)//5
);
console.log('====================无参非匿名立即执行函数写法(8种)======================================');
+function f() {
console.log('+f')
}();
-function f() {
console.log('-f')
}();
~function f() {
console.log('~f')
}();
!function f() {
console.log('!f')
}();
(function f() {
console.log('f外')
})();
(function f() {
console.log('f内')
}());
void function f() {
console.log('void')
}();
new function f() {
console.log('new')
}();
console.log('====================有参非匿名立即执行函数写法(7种)======================================');
console.log(
+function f(x, y) {
return x + y;
}(9, 3)//12
);
console.log(
-function f(x, y) {
return x + y;
}(9, 3)//-12
);
console.log(
~function f(x, y) {
return x + y;
}(9, 3)//-13(-12-1)
);
console.log(
!function f(x, y) {
return x + y;
}(9, 3)//false
);
console.log(
(function f(x, y) {
return x + y;
})(9, 3)//12
);
console.log(
(function f(x, y) {
return x + y;
}(9, 3))//12
);
console.log(
function f(x, y) {
return x + y;
}(9, 3)//12
);
//将函数赋予一个变量则创建函数表达式,赋予一个事件则成为事件处理
var sum = function (x, y) {
return x + y;
}(2, 3)
console.log('sum:' + sum)
var sum1 = function f(x, y) {
return x + y;
}(2, 3)
console.log('sum1:' + sum1)
</script>
</body>
</html>
立即函数之间必须加分号,否则报错