V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
lxy
V2EX  ›  JavaScript

关于变量赋值的小问题

  •  
  •   lxy · 2017-03-10 13:59:19 +08:00 · 1566 次点击
    这是一个创建于 2612 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 还能输出原来的值?

    5 条回复    2017-03-15 11:34:53 +08:00
    chairuosen
        1
    chairuosen  
       2017-03-10 14:24:03 +08:00   ❤️ 2
    赋值 15 改变的是变量 index 这个指针,原来的对象还在, fun(index)是把 index 变量指向的对象传进去。
    SuperMild
        2
    SuperMild  
       2017-03-10 15:56:44 +08:00
    注意执行顺序,在改变 index 之前,已经先执行了 i = index
    LeeSeoung
        3
    LeeSeoung  
       2017-03-10 17:23:30 +08:00
    此 index 非彼 index
    lslqtz
        4
    lslqtz  
       2017-03-10 19:59:26 +08:00
    因为 i != index
    denano
        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 a reference 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.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   865 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 19:30 · PVG 03:30 · LAX 12:30 · JFK 15:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.