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函数中调用它?
我如何使这项工作?
原因是因为onstatechange
被称为事件处理程序,并且this
指针可能指向事件触发的ajaxRequest
对象,而不是指向对象,正如您所期望的那样.
下面的重写将this
变量存储在that
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; } } }