JavaScript/闭包:修订间差异
来自康健生活
| 第17行: | 第17行: | ||
</syntaxhighlight>|{{consoleout|<pre> | </syntaxhighlight>|{{consoleout|<pre> | ||
Hello</pre>}}}} | Hello</pre>}}}} | ||
== 闭包和上下文 == | |||
字节面试一道题,考察的是闭包和变量上下文。 | |||
{{leftrightflex|<syntaxhighlight | |||
lang="javascript"> | |||
var bar = 1; | |||
(() => { | |||
console.log(bar); | |||
bar = 2; | |||
})(); | |||
var foo = 1; | |||
(() => { | |||
console.log(foo); | |||
var foo = 2; | |||
})(); | |||
var biz = 1; | |||
(() => { | |||
console.log(biz); | |||
let biz = 2; | |||
})(); | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
1 | |||
undefined | |||
VM518:3 Uncaught ReferenceError: Cannot access 'a' before initialization | |||
at <anonymous>:3:17 | |||
at <anonymous>:5:3 | |||
</pre>}}}} | |||
== 内存泄露 == | == 内存泄露 == | ||