使用变量“name"不适用于 JS 对象 [英] Using the variable "name" doesn't work with a JS object

查看:31
本文介绍了使用变量“name"不适用于 JS 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

行为可以在这个小片段中看到(作为全局脚本执行):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆