从eval()中分配值

时间:2012-10-07 22:19:29

标签: javascript xmlhttprequest eval

这是我目前的代码(显然删除了不必要的元素):

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");
    };
}

这有效,但它将barbar2分配给foo而不是foo[0]。如何确保将其分配给foo[0]

2 个答案:

答案 0 :(得分:0)

myfunc.js包含一个尚未实例化的匿名JavaScript类(=匿名函数)。因此,在您的主脚本中,eval()仅返回该类。 foo[0]现在可用于实例化该类中的对象;它类似于班级名称。

我的观点是你试图从一个类(而不是一个对象)获取属性,这当然不起作用。所以你基本上有两个选择来解决这个问题:

  1. 创建eval()返回的匿名类的实例:

    foo[0] = new (eval("(" + xhr.responseText + ")"));
    console.log(foo[0].bar1);
    
  2. myfunc.js返回一个(单例)对象而不是一个类:

    new function() {
        this.bar1 = "Hello World";
    }
    
  3. 顺便说一句,在我看来,Quentin说你应该重新考虑你的程序结构......

答案 1 :(得分:0)

我最终使用JSON(如Quentin所建议的)而不是定义自修改功能。 我生成的myfunc.json文件如下所示:

{
    "bar1": "Hello World",
    "bar2": function()
    {
        console.log("this is bar2");
    }
}

至于结构,我并不过分关注它。它只在局域网上运行,旨在展示我对WebGL的一个想法,而不是一个实用的,完全完成的游戏。

相关问题