如何在javascript类中添加回调函数?

时间:2009-01-19 07:02:16

标签: javascript oop class-design callback

javascript中的以下代码给出了错误“this.callback不是函数

function ajaxRequest()
{
    var httpObject;

    this.open = open;
    this.callback = function(){};

    function getHTTPObject()
    {
        if (window.ActiveXObject) 
            return new ActiveXObject("Microsoft.XMLHTTP");
        else if (window.XMLHttpRequest)
            return new XMLHttpRequest();
        else 
        {
            alert("Your browser does not support AJAX.");
            return null;
        }
    }

    function onstatechange()
    {
        if(httpObject.readyState == 4)
        {
            this.callback(httpObject.responseText);
        }

    }


    function open(url, callback)
    {
        httpObject = getHTTPObject();
        if (httpObject != null) 
        {
            httpObject.open("GET", url, true);
            httpObject.send(null);
            this.callback = callback;
            httpObject.onreadystatechange = onstatechange;
        }
    }
}

为什么open方法不将callback参数视为函数?

如果确实如此,为什么我不能在onstatechange函数中调用它?

我如何使这项工作?

1 个答案:

答案 0 :(得分:9)

原因是因为onstatechange被称为事件处理程序,this指针可能指向触发事件的对象,而不是ajaxRequest对象,如你所料。

以下重写将this变量存储在onstatechange()函数可以访问的执行上下文中的名为that的变量中。这应该可以解决问题。

所有这些的长短都是如果你不完全理解Javascript闭包和执行上下文,即使你这样做,你使用框架来做你的AJAX请求要好得多。 jQuery和Prototype是不错的选择。

function ajaxRequest()
{
    var httpObject;

    this.open = open;
    this.callback = function(){};
    var that = this;

    function getHTTPObject()
    {
        if (window.ActiveXObject) 
                return new ActiveXObject("Microsoft.XMLHTTP");
        else if (window.XMLHttpRequest)
                return new XMLHttpRequest();
        else 
        {
                alert("Your browser does not support AJAX.");
                return null;
        }
    }

    function onstatechange()
    {
        if(httpObject.readyState == 4)
        {
                that.callback(httpObject.responseText);
        }

    }


    function open(url, callback)
    {
        httpObject = getHTTPObject();
        if (httpObject != null) 
        {
                httpObject.open("GET", url, true);
                httpObject.send(null);
                this.callback = callback;
                httpObject.onreadystatechange = onstatechange;
        }
    }
}