Javascript 普通JS函数中的回调不';你不总是工作吗?

Javascript 普通JS函数中的回调不';你不总是工作吗?,javascript,function,callback,xmlhttprequest,Javascript,Function,Callback,Xmlhttprequest,我已经编写了一个小型的vanilla JS函数来使用XMLHttpRequest对象。我有一个回调要返回,但由于某种原因,我只能让回调用于onreadystatechange函数,我需要它来处理我的ontimeout和onerror 我的职能: 函数makeHttpRequest(类型、url、超时、回调){ const xhr=new XMLHttpRequest() xhr.open(类型、url、true) xhr.timeout=超时 xhr.ontimeout=()=>{ callba

我已经编写了一个小型的vanilla JS函数来使用XMLHttpRequest对象。我有一个回调要返回,但由于某种原因,我只能让回调用于
onreadystatechange
函数,我需要它来处理我的
ontimeout
onerror

我的职能:

函数makeHttpRequest(类型、url、超时、回调){ const xhr=new XMLHttpRequest() xhr.open(类型、url、true) xhr.timeout=超时 xhr.ontimeout=()=>{ callback.apply('超时错误') } xhr.onreadystatechange=()=>{ if(xhr.readyState==4&&xhr.response!=null){ callback.apply(xhr) } } xhr.onerror=()=>{ callback.apply('generic error') } xhr.send() } 我如何使用该函数:

makeHttpRequest('GET',url,超时,函数(){
const res=this.response!=''?this.response:JSON.stringify({})
// ...
})

this.response
在超时和出错时不包含任何内容。

应用
方法将函数的
this
参数设置为其第一个参数。当发生超时或错误时,按如下方式调用apply:

callback.apply('timeout error');
因此,
这个
值是一个字符串。如果位于,您将看到
字符串
对象没有
.response
属性。这就是为什么
“超时错误”。响应
不包含任何内容(它是
未定义的

如果希望
this.response
包含错误消息,则不要将字符串作为
this
传递。而是将其作为
传递。响应

let error = {
    response: 'timeout error'
}

callback.apply(error)
或者更简单地说:

callback.apply({ response: 'timeout error' })

嗯,取决于错误,可能没有响应?您还期望什么?您不应该使用
回调。应用
。你知道
这个
关键字是如何工作的吗?