write 如何將回調函數添加到一個JavaScript類?



node js callback function example (1)

原因是因為onstatechange被稱為事件處理程序,並且this指針可能指向事件觸發的對象,而不是ajaxRequest對象。

下面的重寫this變量存儲在一個變量中, this變量在onstatechange()函數可以訪問的執行上下文中調用。 這應該解決這個問題。

所有這一切的長短都是,如果你不完全理解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;
        }
    }
}

下面的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函數中調用它?

我如何做這項工作?





callback