Last active
April 2, 2017 05:42
-
-
Save tvytlx/61e61522b342ced59510c7a8e4f31fe7 to your computer and use it in GitHub Desktop.
这片代码解释了js(es6)的两个问题:let和var的区别,函数传参是 by value 还是 by reference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
f = (i)=>{ | |
return ()=>{return i;} | |
} | |
var a = [] | |
var b = [] | |
var c = [] | |
(()=>{ | |
for(var i=0; i<5; i++){ | |
// 函数传参传的是这个参数的reference value,不是参数自己本身的地址,所以传进去的是指向不同内存的地址。 | |
a.push(f(i)) | |
} | |
})() | |
(()=>{ | |
for(var i=0; i<5; i++){ | |
// i的作用域在外面的函数里,所以整个循环,i自身没变,但i的reference value在变, | |
// 被插到a里的匿名函数的是i自身,所以最后要看i的reference value指向哪里,a里面的这些i就永远指向哪里了。 | |
b.push(()=>{return i;}) | |
} | |
})() | |
(()=>{ | |
for(let i=0; i<5; i++){ | |
// 在5次循环的每一次,i在for的块作用域里都是新的,各自的reference value当然也不同, | |
// 所以被插到a里的匿名函数里的i是指向不同的值的新的i。 | |
c.push(()=>{return i;}) | |
} | |
})() | |
console.log(a.map((f)=>f()))// 0,1,2,3,4 | |
console.log(b.map((f)=>f()))// 5,5,5,5,5 | |
console.log(c.map((f)=>f()))// 0,1,2,3,4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment