代码之家  ›  专栏  ›  技术社区  ›  Å ime Vidas Zim84

JavaScript:使用点符号和括号符号时的不同行为[重复]

  •  4
  • Å ime Vidas Zim84  · 技术社区  · 14 年前

    这个JavaScript片段

    var x = window.foo;
    window.x = null;
    alert( window.bar === undefined );
    

    警报为“真”。

    但是,这个片段

    var x = window.foo;
    window[x] = null;
    alert( window.bar === undefined );
    

    警报“假”。

    这是怎么回事?

    (我在最新的Chrome浏览器中运行这段代码,它位于HTML页面中,没有其他JavaScript代码。)

    更新

    正如他在下面的评论中巧妙地总结的那样,我错误地认为 window.x window[x] 相当于。这是不对的。 窗口.x 相当于 window["x"] .

    2 回复  |  直到 14 年前
        1
  •  3
  •   Å ime Vidas Zim84    14 年前

    你所经历的行为是因为 undefined 全局对象的属性,在任何 ECMAScript 3 基于实施。(最新的Chrome版本正在实现ES5,但这种行为仍然存在)。

    让我们检查第二个片段:

    var x = window.foo;
    window[x] = null;
    alert( window.bar === undefined );
    

    这个 x 变量将保存 未定义 价值,因为 foo 属性不存在。

    通过分配 window[x] = null ,您将重写 未定义 属性:

    window[x] = null; // is equivalent to
    window['undefined'] = null; // or
    window.undefined = null; //
    

    (在第一个片段中,当您指定 window.x = null ,您正在创建名为 "x" window 对象)

    因此(在第二个片段中) 未定义 财产将持有 null ,和 window.bar 将产生 未定义 :

    alert( window.bar === undefined ); // false
    alert( undefined  === null ); // false
    

    这个 未定义 属性未指定为 { ReadOnly } 在ECMAScript 3上,(和他的朋友们 NaN , Infinity ).

    这在ECMAScript 5中已经改变,这些属性被描述为不可写的。

        2
  •  1
  •   Ivo Wetzel    14 年前
    var x = window.foo;  // set the local variable x to the contents of window.foo
    window.x = null; // set property x on window to null
    

    在这里你可以直接设置属性 x 为空。

    var x = window.foo; // set the local variable x to the contents of window.foo
    window[x] = null; // set they key with the value of x to null
    

    在这里,您将属性设置为 key 在窗口对象上。那是哪把钥匙?这取决于 ,如果 bar 你将有效地 window.bar = null 如果 blub 你会的 window.blub = null .

    有关此方面的详细信息,请访问MDC:
    https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators