在回调方法中使用 Javascript this Context

标签 javascript ajax this

我是 Javascript 新手。这段代码大部分都有效,但发生了一些奇怪的事情。当我调用 .send()它触发异步请求并正常返回,但问题是 this调用 WebCall.prototype.__stateChangedCallback 时的上下文方法。在 Chrome 中 this是 XMLHttpRequest 对象,而我认为它将是 WebCall对象代替。谁能给我解释一下这是为什么?

function log (message) {
    if(typeof console == "object") {
        console.log(message);
    }
}

function WebCall () {
    var __callMethod;
    this.__callMethod = this.createXmlHttpRequest();
}

WebCall.prototype.createXmlHttpRequest = function () {
    if(window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

WebCall.prototype.beginGet = function(url) {
    this.__callMethod.open("GET", url, true);
    this.__callMethod.onreadystatechange = this.__stateChangedCallback;
    this.__callMethod.send();
}

WebCall.prototype.__stateChangedCallback = function(readyState, status) {
    // this points to the XMLHttpRequest rather than the WebCall object WHY??!
    var request = this.__callMethod;
    if(request.readyState == 4) {
        if (request.status == 200) {
            this.onRequestCompleted(request);
        } else {
            this.onRequestFailed(status, request);
        }
    }
}

WebCall.prototype.onRequestCompleted = function (request) {

}

WebCall.prototype.onRequestFailed = function(status, request) {
    log("Request failed status= " + status);
}

最佳答案

WebCall.prototype.__stateChangedCallback 中的只是对匿名函数的引用:

WebCall.prototype.__stateChangedCallback = function(readyState, status) {
   //......................................^^^^ anonymous function
}

这一行:

this.__callMethod.onreadystatechange = this.__stateChangedCallback;

意味着,您有另一个对同一个匿名函数的引用。此匿名函数不是您的原型(prototype)对象的一部分。您只是在您的原型(prototype)对象中引用它。

解决方法是这样的:

var that = this;
this.__callMethod.onreadystatechange = function(readyState, status){
    //Calling anonymous function with 'this' context
    WebCall.prototype.__stateChangedCallback.apply( that, arguments );
}

关于在回调方法中使用 Javascript this Context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671103/

相关文章:

JQuery 和 'this' 对象

javascript - 如何将相同的功能应用于同名的不同div?

javascript - 数据表 - ajax 成功

php - PHP 刷新可以与 jQuery ajax 一起使用吗?

javascript - 该函数可以工作,但报告 this.refresh() 不是一个函数

c# - .NET 文档中 'this' 关键字的定义

javascript - 为什么 Math.prototype 未定义?

javascript - 奇怪的行为 - <li> 菜单项在 Internet Explorer 中移动到下一行,在其他浏览器上很好

javascript - 无法运行 node.js 和 npm 示例聊天

php - 如何从 jquery 中的 php Controller 检索数据