涉及变量提升和闭包
<script type="text/javascript">
//ES5
const callbacks = []
for(var i = 0; i<3; i++){
callbacks[i] =function () {
return i*2
}
}
console.table([
callbacks[0](),
callbacks[1](),
callbacks[2]()
]);
//ES6
const callbacks = []
for(let i = 0; i<3; i++){
callbacks[i] =function () {
return i*2
}
}
console.table([
callbacks[0](),
callbacks[1](),
callbacks[2]()
]);
</script>
<script type="text/javascript">
//ES5
((function () {
const foo =function () {
return 1
}
console.log("foo()===1",foo() ===2)
;((function () {
var foo =function () {
return 2
}
console.log("foo()===2",foo() === 2)
})())
})())
//ES6
{
function foo() {
return 1
}
console.log('foo()===1',foo() === 1);
{
function foo() {
return 2
}
console.log('foo()===2',foo() === 2)
}
}
</script>