Repository navigation
Expand file tree
/
Copy pathimmediately-invoked-function-expression.html
More file actions
92 lines (66 loc) · 2.08 KB
/
Copy pathimmediately-invoked-function-expression.html
File metadata and controls
92 lines (66 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Immediately-Invoked Function Expression - 立即调用的函数表达式</title>
</head>
<body>
<p>
Immediately-Invoked Function Expression
<br />
An immediately-invoked function expression (or IIFE, pronounced "iffy"[1]) is a JavaScript design pattern which produces a lexical scope using JavaScript's function scoping
<br />
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
</p>
<script>
//变量声明部分 ---------------------------------------------------------------------------------------------
var log = 'abc';
//方法声明部分 ---------------------------------------------------------------------------------------------
var printStr = function(str){
console.log(str);
};
function makeCounter(){
//'i' 的作用域只在 makeCounter 方法中
var i = 0;
return function(){
console.log(++i);
}
};
//测试使用部分 ---------------------------------------------------------------------------------------------
//Part I
var counter = makeCounter();
// counter(); //1
// counter(); //2
var counter2 = makeCounter();
// counter2(); //1
// counter2(); //2
(function(){
//全局变量可以直接获取
// console.log(log); //abc
var person = {
name: 'Jim'
};
//printStr('123');
//Uncaught TypeError: printStr is not a function
//方法需要引用才能使用
})();
//Part II
(function(printStr){
// printStr('two'); //two
}(printStr));
//Part III
//Self-executing function
//function foo() { foo(); }
//foo();
//Uncaught RangeError: Maximum call stack size exceeded
//Self-executing anonymous function
//var foo = function() { arguments.callee(); };
//foo();
//Uncaught RangeError: Maximum call stack size exceeded
// 常用写法
;(function () {
//do something
}())
</script>
</body>
</html>