这是我当前的代码(明显删除了不必要的元素):
var foo = new Array();
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
foo[0] = eval("(" + xhr.responseText + ")");
// After this point, I want to be able to reference
// foo[0].bar1
// and
// foo[0].bar2()
}
}
xhr.open("GET", "myfunc.js", true);
xhr.send();
这是myfunc.js
的内容,但它不起作用。
function() {
this.bar1 = "Hello World";
this.bar2 = function()
{
console.log("this is bar2");
};
}
这可行,但它将 bar
和 bar2
分配给 foo
而不是 foo[0]
。我如何确保它将它们分配给 foo[0]
?
最佳答案
myfunc.js
包含一个尚未实例化的匿名 JavaScript 类(= 匿名函数)。因此,在主脚本中,eval()
仅返回该类。 foo[0]
现在可用于实例化该类的对象;它类似于类名。
我的观点是,您试图从类(而不是对象)获取属性,这当然是行不通的。所以你基本上有两种选择来解决问题:
创建由
eval() 返回的匿名类的实例
:foo[0] = new (eval("(" + xhr.responseText + ")")); console.log(foo[0].bar1);
从
myfunc.js
返回一个(单例)对象而不是类:new function() { this.bar1 = "Hello World"; }
顺便说一句,在我看来,昆汀说你应该重新考虑程序的结构有一个很好的观点......
关于javascript - 从 eval() 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773359/