Javascript对象中的变量范围 [英] Variable scope in Javascript Object

查看:62
本文介绍了Javascript对象中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中发现了对象的概念。我正在制作一个RSS Parser,我有一个错误(评论)。

I'm discovering the concept of "objects" in JavaScript. I'm making an RSS Parser, and I have an error (commented).

function MyParser (feed_url) {  // Construct
    "use strict";
    this.feedUrl = feed_url;
    this.pubArray = [];

    if (typeof (this.init_ok) == 'undefined') {
        MyParser.prototype.parse = function () {
        "use strict";
        var thisObj = this;
        $.get(this.feedUrl, function (data, textStatus, jqXHR) {
            if (textStatus == 'success') {
                var xml = jqXHR.responseXML,
                    //lastBuildDate = new Date($(xml).find('lastBuildDate').text());
                    items = $(xml).find('item');
                items.each(function () {
                    var pubSingle = thisObj.makeObj($(this).find('pubDate').text(),
                                                    $(this).find('link').text(),
                                                    $(this).find('title').text(),
                                                    $(this).find('description').text(),
                                                    $(this).find('encoded').text(),
                                                    $(this).find('commentRss').text(),
                                                    $(this).find('comments').last().text());
                    thisObj.pubArray.push(pubSingle);
                });
                console.log(thisObj.pubArray); // OK
            }
        }, 'xml');
        console.log(this.pubArray); // Empty
        return (this.pubArray);
    };

    MyParser.prototype.makeObj = function (pubDate, pubLink, pubTitle, pubDesc, pubContent, pubComCount, pubComLink) {
        "use strict";
        var pubSingle = {};
        pubSingle.pubDate = new Date(pubDate);
        pubSingle.pubLink = pubLink;
        pubSingle.pubTitle = pubTitle;
        pubSingle.pubDesc = pubDesc;
        pubSingle.pubContent = pubContent;
        pubSingle.pubComCount = pubComCount;
        pubSingle.pubComLink = pubComLink;
        return (pubSingle);
    };
}
this.init_ok = true;
}

如果查看 console.log() ,你会看到 // OK 这一行正在输出我的数组。

If you look at the console.log(), you'll see that the line // OK is outputting my array correctly.

但是后来,当从 $。get 返回时,我的数组是空的。

But later, when returning from $.get, my array is empty.

有没有人有个主意为什么,以及如何纠正它?

Does anybody have an idea why, and how to correct that please?

推荐答案

这不是变量范围的问题。这里的问题是你正在使用异步流,而你没有正确思考流程。

This is not a problem with variable-scope. The problem here is that you're working with asynchronous flow and you're not thinking correctly the flow.

让我解释一下:

当您执行 .get 时,您将触发一个并行异步进程,该进程将从浏览器请求信息,但是您的主程序的流程仍在继续,所以你进入 return 语句,你的数组还没有填满你的get方法的响应。

When you do your .get, you fire a parallel asynchronous process that will request information from the browser, but your main program's flow keeps going, so when you get to your "return" statement, your array has not been filled yet with the response from your get method.

你应该在get回调中使用你的数组,而不是在它之外,因为你不能保证数组将拥有你需要的信息。

You should use your array from inside the get callback and not outside of it, since you can't guarantee that the array will have the information you need.

它有什么意义吗?

告诉我!

进一步说明

根据你的评论,你仍然会做这样的事情:

According to your comments, you're still doing something like this:

var results = MyParser(feed_url);
//使用results.pubArray的代码

var results = MyParser(feed_url); //code that uses results.pubArray

你不能这样做。即使您在 .get 回调中设置了pubArray,也只是在调用 MyParser 并且在调用 .get 回调之前。
您需要做的是从 .get 回调中调用程序逻辑的下一步...这是您可以确定的唯一方法 pubArray 填充了适当的数据。

And you cannot do that. Even though you're setting your "pubArray" inside your .get callback, you're trying to use pubArray right after you called MyParser and that's before the .get callback is called. What you have to do, is call your next step on your program's logic from within the .get callback... that's the only way you can be sure that the pubArray is filled with proper data.

我希望这更清楚。

这篇关于Javascript对象中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆