[英]Why does declaring a variable named values as an object returns type of function in Firefox
I have used var values = {};
我用过
var values = {};
in a JavaScript file. 在JavaScript文件中。 However when I test my application on Firefox
typeof(values)
returns function instead of object. 但是,当我在Firefox上测试我的应用程序时,
typeof(values)
返回函数而不是object。 This can easily be tested within Firefox console window. 这可以在Firefox控制台窗口中轻松测试。 As this variable has been used many times in my application;
由于此变量已在我的应用程序中多次使用; changing it's name may not be a feasible solution.
更改它的名称可能不是一个可行的解决方案。 My questions are:
我的问题是:
The problem is your assignment tries to change the read-only property window.values
which is a function, a console utility. 问题是你的赋值试图改变只读属性
window.values
是一个函数,一个控制台实用程序。
You don't have such problem if you do it in an inner scope: 如果在内部范围内执行此操作,则不会出现此问题:
(function(){ var values = {}; console.log(typeof values) })()
The difference between Chrome and Firefox is that Chrome doesn't define this property as read-only. Chrome和Firefox之间的区别在于Chrome没有将此属性定义为只读。
That's just an artifact of the Firefox console, it doesn't affect your real code. 这只是Firefox控制台的一个工件,它不会影响您的真实代码。 If you use
typeof values
in your actual script code, you'll see that it's undefined
(or object
if you create it as shown in your question). 如果在实际的脚本代码中使用
typeof values
,您将看到它是undefined
(如果您按照问题所示创建它,则为object
)。
Firefox's console provides values
as a means of seeing the values of an object: Firefox的控制台提供
values
作为查看对象值的方法:
>> values({foo: "bar"}) -> Array [ "bar" ]
There are other functions available in the Firefox console; Firefox控制台中还有其他功能; they're documented here .
他们在这里记录 。
Chrome / Chromium has a bunch of them as well (including values
), documented here . Chrome / Chromium也有很多(包括
values
), 在此处记录 。
Is there a way to force this variable name as an object?
有没有办法强制将此变量名称作为对象?
In real script code, not the console, there's no problem using values
. 在真正的脚本代码中,而不是控制台,使用
values
没有问题。 However, I suggest avoiding creating globals, since the global namespace is very crowded. 但是,我建议避免创建全局变量,因为全局命名空间非常拥挤。
What other variable names should i be concerned in order to avoid this problem?
我应该关注哪些其他变量名称以避免此问题?
name
and title
are common ones people trip over. name
和title
是人们绊倒的常见name
。 This is another reason not to use global variables. 这是不使用全局变量的另一个原因。 Instead, put your code in a scoping function:
相反,将您的代码放在作用域函数中:
(function() {
// Your code here
})();
Because by doing so in firefox, you're trying to override/re-assign the global read-only window object values which type is function 因为在firefox中这样做,你试图覆盖/重新分配类型为函数的全局只读窗口对象值
window.values // its a function
Chrome however doesnt treat values
as a read-only object 但Chrome并不将
values
视为只读对象
In order to make it works as you wish in Firefox, you need to place it inside a function 为了使它在Firefox中正常工作,您需要将其放在函数中
function test() {
var values = {};
console.log(typeof values); // typeof: object
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.