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

为什么在这个有趣的Javascript代码片段中U变量设置为NULL?

  •  1
  • jebberwocky  · 技术社区  · 14 年前

    var u = {};
    var x = y = z = {"cvalue":"cell", "call":function(){alert(this.cvalue);}};
    
    (function(){u=x;/*change all cvalue in x,y, z, u*/ u.cvalue = "notcell";})();
    
    if(u == x && x == y && y == z && z == u){
        u.call();
    }
    
    //only u goes to null
    u = null;
    //x,y,z stay same
    alert(x.cvalue);
    

    想知道为什么吗 u = null 仅适用于 u ?

    3 回复  |  直到 14 年前
        1
  •  6
  •   Daniel Vassallo    14 年前

    变量实际上并不包含一个对象,只是包含一个对象的引用。通过分配 u null 我得去拿那个东西。

    一个更基本的例子:

    var x = { 'name': 'Bob' };
    var y = x;
    
    console.log(x);   //  Object { name="Bob"}
    console.log(y);   //  Object { name="Bob"}
    
    y.name = 'Jack';
    
    console.log(x);   //  Object { name="Jack"}
    console.log(y);   //  Object { name="Jack"}
    
    x = null;
    
    console.log(x);   //  null
    console.log(y);   //  Object { name="Jack"}
    

    x . 它被保存在记忆的某个地方 y = x ,我们将引用复制到 y ,因此 是的 开始引用同一对象。设置 无效的 只需删除 保持对象,使实际对象不受影响。如果我们要设置 是的 无效的 ,或者其他任何东西,垃圾收集器最终会将该对象进行销毁。

        2
  •  1
  •   Yevgeny Simkin    14 年前

    丹尼尔是对的,但你必须小心,因为在Javascript中,你有时处理的是副本,有时处理的是原件。例如。。。

    var a = new Object();
    a.foo = new function(){alert("I exist")};
    
    var b = a;
    
    b.foo = null;//this erases the function from both a and b (technically, there is only one since a and b point to the same place in memory).
    
    a.foo();//this now fails since there is no longer a function called foo
    
    b = null;//this does NOT affect a in any way as per Daneiel Vassallo's explanation.
    
        3
  •  1
  •   some    14 年前

    将完全相同的对象指定给x、y和z,而不是其值的副本,而是完全相同的对象。

    在伪代码中:

    var u = OBJECT_A // u points to OBJECT_A
    
    var x = y = z = OBJECT_B // x y and z points to OBJECT_B
    
    (function(){
        u=x;  // Drop reference to OBJECT_A and point to OBJECT_B
    
        /*change all cvalue in x,y, z, u*/
        u.cvalue = "notcell";  //Changes the cvalue in OBJECT_B
                               // Remember x,y,z, and u points to OBJECT B
                               // so x.cvalue, y.cvalue, z.cvalue and u.cvalue is the same
    })();
    
    if(u == x && x == y && y == z && z == u){
       u.call();
    }
    
    //only u goes to null
    u = null;  // Drop reference to OBJECT_B and point to NULL.
    
    
    //x,y,z still points to OBJECT_B
    alert(x.cvalue);