使用变量“name”不适用于JS对象 [英] Using the variable "name" doesn't work with a JS object
问题描述
可以在这个小片段中看到行为(将其作为全局脚本执行):
The behaviour can be seen in this little snippet (execute it as a global script):
var name = {};
name.FirstName = 'Tom';
alert(name.FirstName);
警告在Chrome中产生 undefined
但是有效在IE和Firefox中。当我这样做时,我也会得到一个奇怪的值
The alert yields undefined
in Chrome but works in IE and Firefox. I also get a weird value when I do
alert(name);
推荐答案
window.name 有一个特殊用途,应该是一个字符串。 Chrome似乎明确地将其转换为字符串,因此 var name = {};
实际上最终会给出全局变量 name
(即 window.name
)值[object Object]
。由于它是原始的,属性( name.FirstName
)不会坚持。
window.name has a special purpose, and is supposed to be a string. Chrome seems to explicitly cast it to a string, so var name = {};
actually ends up giving the global variable name
(i.e. window.name
) a value of "[object Object]"
. Since it's a primitive, properties (name.FirstName
) won't "stick."
绕过这个问题,不要将 name
用作全局变量。
To get around this issue, don't use name
as a global variable.
这篇关于使用变量“name”不适用于JS对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!