当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在javascript类中添加回调函数?》经验,为你挑选了1个好方法。

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;
        }
    }
}

为什么不打开方法将回调参数视为函数?

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

我如何使这项工作?



1> Triptych..:

原因是因为onstatechange被称为事件处理程序,并且this指针可能指向事件触发的ajaxRequest对象,而不是指向对象,正如您所期望的那样.

下面的重写将this变量存储在thatonstatechange()函数可以访问的执行上下文中调用的变量中.这应该解决这个问题.

所有这些的长短都是如果你不完全理解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;
        }
    }
}

推荐阅读
女女的家_747
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有