代码之家  ›  专栏  ›  技术社区  ›  lovemyjob

为什么Java脚本中不自动更新变量?(范围?)[副本]

  •  -1
  • lovemyjob  · 技术社区  · 7 年前

    我有以下代码:

    var obj = {
        car: "volvo",
        speed: 20
    };
    
    var x = obj.speed;
    obj.speed = 500;
    console.log(x);
    console.log(obj.speed);
    
    obj.speed = 1000;
    var y = obj.speed;
    console.log(y);
    

    在您将x记录到控制台时,人们会认为x是500,但它仍然是20。安慰对数(目标速度)结果为500。

    你能告诉我为什么会这样吗?

    我知道如果我交换它们的位置:var x声明和obj。速度=500,它将指向500。就像y变量一样

    但为什么呢?在记录x变量之前,代码是否未检查其最后一个值?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Anurag Singh Bisht    7 年前

    分配时 x obj.speed ,这与为基元变量赋值类似。

    如果指定的值为 obj to变量 y ,然后它将被更新,因为它将引用相同的内存位置。

    var obj = {
        car: "volvo",
        speed: 20
    };
    
    // Object is a referece data type.
    // But you are assigining value of obj.speed which is primitive to the the x
    // Hence value of x won't change even if you change the value of obj.speed.
    
    var x = obj.speed;
    obj.speed = 500;
    console.log(x);
    
    
    // But if you assign the value of object to another variable `y`
    // Now, y will be pointing to the same memory location as that of obj
    // If you update the obj, then the value of y will also get updated
    var y = obj;
    obj.speed = 1000;
    console.log(y);
    console.log(obj);