在JavaScript中访问外部作用域

Jak*_*les 5 javascript scope

所以我在这里有这个JS代码,我试图从成功和错误回调中设置obj,但显然toLinkInfo函数范围不是那些的父范围?无论怎样,我总是从这个函数中恢复.我尝试了一堆东西,但无法让它工作,我想我已经习惯了C和朋友:)我怎么能让它工作?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

cwa*_*ole 3

这是因为 AJAX 调用是异步的——它们发生在与上下文的其余部分不同的时间。

尝试给它一个回调函数(下面称为回调)。

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
Run Code Online (Sandbox Code Playgroud)

虽然这种方法无法提供与内联调用所有内容完全相同的结果,但它的优点是允许 Web 的异步特性。