
var index = { data: 10 }; function par() { function fun(i) { index = 15; console.log(i.data + ' ' + index); } fun(index); } par(); console.log(index); 输出 10 15\n15
问题是,在 fun 内部不是已经改变全局变量 index 的值了吗,为什么 i.data 还能输出原来的值?
1 chairuosen 2017-03-10 14:24:03 +08:00 赋值 15 改变的是变量 index 这个指针,原来的对象还在, fun(index)是把 index 变量指向的对象传进去。 |
2 SuperMild 2017-03-10 15:56:44 +08:00 注意执行顺序,在改变 index 之前,已经先执行了 i = index |
3 LeeSeoung 2017-03-10 17:23:30 +08:00 此 index 非彼 index |
4 lslqtz 2017-03-10 19:59:26 +08:00 因为 i != index |
5 denano 2017-03-15 11:34:53 +08:00 js 函数传参永远都是值传递,如果参数是对象的话,传的是对象引用的内存地址。 你的问题里 i 指向的是一开始 index 的内存地址,后面执行的 index=15 让 index 指向了新的地址,但是 i 还是指向最初的地址。 如果 index=15 改成 index.data=15 的话,那么 i 会跟着一起变。 参考 http://stackoverflow.com/questions/6605640/Javascript-by-reference-vs-by-value Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is areference to the object. Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object. However, changing a property of an object referenced by a variable does change the underlying object. |