JavaScript/立即调用函数表达式:修订间差异
来自康健生活
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” 标签:ReplaceText 移动版编辑 移动版网页编辑 |
|||
| (未显示同一用户的10个中间版本) | |||
| 第1行: | 第1行: | ||
== 引言 == | == 引言 == | ||
立即调用函数表达式(即时函数),IIFE,Immediately Invoked Function Expression。 | 立即调用函数表达式(即时函数),IIFE,Immediately Invoked Function Expression。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
(function () { | (function () { | ||
statements | statements | ||
})(); | })(); | ||
</syntaxhighlight | </syntaxhighlight>|<syntaxhighlight lang="javascript"> | ||
(function () { | (function () { | ||
statements | statements | ||
| 第17行: | 第16行: | ||
== 作用域 == | == 作用域 == | ||
=== 验证作用域 === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
for(var i=0;i<3;i++){} | |||
console.log(i);</syntaxhighlight>|{{consoleout|<syntaxhighlight lang="text"> | |||
3 | |||
</syntaxhighlight>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript">Insert comment here</syntaxhighlight>|{{consoleout|<pre>hffgh | |||
</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
(function(){ | |||
for(var i=0;i<3;i++){} | |||
})(); | |||
</syntaxhighlight>|{{consoleout|<pre>Uncaught ReferenceError: i is not defined | |||
at <anonymous>:1:13</pre>}}}} | |||
=== 临时作用域传参 === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
for(var i=0;i<3;i++){ | |||
(function(n){ | |||
setTimeout(function(){ | |||
console.log(n); | |||
},0); | |||
})(i); | |||
} | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
0 | |||
1 | |||
2 | |||
</pre>}}}} | |||
=== 可读性 === | |||
=== undefined === | |||
在函数体内部,undefined 会被赋值。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
function foo(){ | |||
var undefined = []; | |||
console.log(typeof undefined); | |||
console.log(undefined); | |||
} | |||
foo(); | |||
</syntaxhighlight>|{{consoleout|<pre>object | |||
[] | |||
</pre>}}}} | |||