对象的Javascript变量赋值返回字符串 [英] Javascript variable assignment of object returns string
问题描述
我正在尝试运行以下代码:
I am trying to run the following code:
var status = null;
$.ajax({
type: "GET",
url: "/status",
success: function(data, textStatus, jqXHR){
status = data;
},
error: function(jqXHR, textStatus, errorThrown){
console.error(textStatus + ": " + errorThrown);
}
});
有趣的部分是以下行: status = data;
The interesting part is the following line: status = data;
在调试器中我可以看到 data
的值为 Object {7100665:0,8800798:0}
。 jQuery正确地将从服务器返回的JSON字符串解析为一个对象。
In the debugger I can see that data
has the value Object {7100665: 0, 8800798: 0}
. jQuery correctly parses the JSON-string returned from the server into an object.
然而,一行后面的全局变量 status
的值为[object Object]
,其行为类似于字符串对象 - 字符串没有按预期分配给它的对象。
However, one line later the global variable status
has the value "[object Object]"
and behaves like a string object - string does not have the object assigned to it as expected.
在分配中看起来有一个隐含的 typeof
调用,这不可能,对吧?是否还有一些我不知道的事情? ajax调用的 Content-Type
是 application / json
。
It looks like there was an implicite typeof
call in the assignment going on, which cannot be, right? Is there some more going on that I am not aware of? The Content-Type
of the ajax call is application/json
.
我错过了什么/做错了什么?
What am I missing/doing wrong?
推荐答案
status
作为全局变量实际上是 窗口。 status
,这是一个(非标准)主机对象,可让您在实现它的浏览器中操作状态栏的文本。它的值被假定为一个字符串,因此你赋给它的任何值都将被静默强制转换成一个字符串。
status
as a global variable is actually window.status
, which is a (non-standard) host object that lets you manipulate the text of the status bar in browsers that implement it. Its value is assumed to be a string, so any value that you assign to it will be silently coerced into a string.
真正的问题是你污染了它带变量的全局范围。使用IIFE,这不是问题:
The real problem is that you're polluting the global scope with variables. Use an IIFE and this will not be an issue:
(function() {
var status = null;
})();
这篇关于对象的Javascript变量赋值返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!