开发者

Accessing outer scope in JavaScript

So I've got this JS code here, and I'm trying to set obj from the success and error callbacks, but apparently the toLinkInfo function scope is not a parent scope of those? I always get null back from this function no matter what. I tried a bunch of stuff but couldn't get it to work, I guess I'm too used to C & friends :) How can I get this to work?

LinkInfoGrabber.prototype.toLinkInfo = function() {
    var obj = null;
    $.ajax({
        url: this.getRequestUrl(),
        success: function(raw) {
            obj = new LinkInfo(raw);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            obj = new LinkInfoException(jqXHR, textStatus, errorThrown);
        },
        dataType: 'html'
    });

    if (obj instanceof LinkInfo) {
        return obj;
    } else {
 开发者_运维技巧       throw obj;
    }
}


That's because AJAX calls are asynchronous -- they happen at a different time from the rest of the context.

Try giving it a callback function( called callback below ).

LinkInfoGrabber.prototype.toLinkInfo = function(callback) {
    $.ajax({
        url: this.getRequestUrl(),
        success: function(raw) {
            callback( new LinkInfo(raw) );
        },
        error: function(jqXHR, textStatus, errorThrown) {
            obj = new LinkInfoException(jqXHR, textStatus, errorThrown);
        },
        dataType: 'html'
    });
}

var l = new LinkInfoGrabber()
l.toLinkInfo(console.log) //replace console.log with something meaningful

While this approach does not provide exactly the same result as being able to call everything inline, it has the benefit of allowing for the asynchronous nature of the web.


This code:

if (obj instanceof LinkInfo) {
        return obj;
    } else {
        throw obj;
    }

runs immediately after you START the ajax call, but obj is not set until the ajax call finishes successfully. This is a common misunderstanding. The Ajax call is asynchronous. Your call to $.ajax() starts the asynchronous call and then the rest of your function immediately executes. The success handler is called only when the ajax call succeeds (some time later). You can't return obj from your function. You have to handle obj in your success handler and then call anything further that wants to use it from the success handler.


You're returning obj before the call to ajax returns, so it's not set to anything but null when it is returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜