JavaScript:使用点符号和方括号符号时的行为不同 [英] JavaScript: Different behavior when using dot-notation vs. bracket-notation
问题描述
此JavaScript代码段
This JavaScript snippet
var x = window.foo;
window.x = null;
alert( window.bar === undefined );
提示"true".
但是,此代码段
var x = window.foo;
window[x] = null;
alert( window.bar === undefined );
提示"false".
这是怎么回事?
(我正在HTML页面中最新的Chrome浏览器中运行此代码,其中没有其他JavaScript代码.)
(I am running this code in the latest Chrome browser inside a HTML page with no other JavaScript code in it.)
更新
Update
@elusive在下面的评论中巧妙地总结了一下,我误认为 window.x
和 window [x]
是等效的.那是不对的. window.x
等同于 window ["x"]
.
As @elusive cleverly summed up in his comment below, I mistakingly assumed that window.x
and window[x]
are equivalent. That is not correct. window.x
is equivalent to window["x"]
.
推荐答案
您遇到的行为是因为Global对象的 undefined
属性在任何 ECMAScript 3 的实现.(最新的Chrome版本正在实现ES5,但此行为仍然存在).
The behavior that you are experiencing is because the undefined
property of the Global object, is mutable on any ECMAScript 3 based implementation. (latest Chrome versions are implementing ES5, but this behavior is still present).
让我们检查第二个片段:
Let's examine the second snippet:
var x = window.foo;
window[x] = null;
alert( window.bar === undefined );
由于 foo
属性不存在,因此 x
变量将保留 undefined
值.
The x
variable will hold the undefined
value, since the foo
property does not exist.
通过分配 window [x] = null
,您将覆盖 undefined
属性的值:
By assigning window[x] = null
, you are overriding the value of the undefined
property:
window[x] = null; // is equivalent to
window['undefined'] = null; // or
window.undefined = null; //
(在第一个代码段中,当您分配 window.x = null
时,您正在 window
"x" 的属性>对象.)
(In your first snippet, when you assign window.x = null
, you are creating a property named "x"
on the window
object.)
因此(在第二段代码中), undefined
属性将保留 null
,而 window.bar
将产生 undefined
:
Therefore (in your second snippet), the undefined
property will hold null
, and window.bar
will produce undefined
:
alert( window.bar === undefined ); // false
alert( undefined === null ); // false
未在ECMAScript 3上将 undefined
属性未指定为 {ReadOnly}
((以及他的朋友 NaN
, Infinity
).
The undefined
property was not specified as { ReadOnly }
on ECMAScript 3, (along with his friends NaN
, Infinity
).
这在ECMAScript 5中已更改,这些属性被描述为不可写.
This has changed in ECMAScript 5, those properties are described as non-writables.
这篇关于JavaScript:使用点符号和方括号符号时的行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!