简体   繁体   English

为什么这个对象突然变得不确定?

[英]Why is this object suddenly undefined?

here is my JavaScript code: 这是我的JavaScript代码:

var Model =
{
    get: function(id)
    {
        return this.data[id];
    },

    data: {},

    init: function()
    {   
        var self = this;

        $.getJSON(urlToServer, function(data)
        {
            $.each(data, function(i, object)
            {
                self.data[object.id] = object;
                console.log(object.id); // output is: 1, then 2, then 3
            });
        });
    }
};

Model.init();
console.log(Model); // output is the initialized object with children objects 1, 2, 3
console.log(Model.get(1)); // output is undefined

As you can see from the console output i put in the comments, everything works fine until the last line of code. 从控制台输出中可以看到,我在注释中输入了所有内容,直到最后一行代码为止。 I define a Model and initialize it with some JSON objects provided by the server. 我定义一个模型,并使用服务器提供的一些JSON对象对其进行初始化。 But all of a sudden, when i try to access a single child object through the get() method, the Model appears to be undefined. 但是突然之间,当我尝试通过get()方法访问单个子对象时,该模型似乎未定义。

I just don't get it, please help me out. 我不明白,请帮帮我。

Thanks. 谢谢。

Looking at the sample code you used, Model.get(1) will always return undefined. 查看您使用的示例代码,Model.get(1)将始终返回未定义。

$.getJSON is an AJAX call that does not necessarily return immediately (known as asynchronous). $ .getJSON是一个AJAX调用,不一定立即返回(称为异步)。 You will need to use the callback you supplied to $.getJSON to fire off any logic depending on Model.get(1), otherwise it will remain undefined. 您将需要使用提供给$ .getJSON的回调来触发依赖于Model.get(1)的任何逻辑,否则它将保持不确定状态。

$.getJSON是一个异步请求,在调用Model.get()之前必须等待响应

You trying to retrieve object's field "142". 您试图检索对象的字段“ 142”。 I guess you get from json only "1", "2" and "3" id's? 我想你只能从json获得“ 1”,“ 2”和“ 3” ID吗? If i'm right then get function return to you correct answer because no object field "142" exists. 如果我是正确的,那么get函数将为您返回正确的答案,因为不存在对象字段“ 142”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM