gpt4 book ai didi

javascript - 如何向 javascript 类添加回调函数?

转载 作者:行者123 更新时间:2023-12-02 19:45:43 26 4
gpt4 key购买 nike

以下 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方法不把回调参数当作函数处理?

如果是的话,为什么我不能在 onstatechange 函数中调用它?

我该如何完成这项工作?

最佳答案

原因是因为 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;
}
}
}

关于javascript - 如何向 javascript 类添加回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/456767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com