所以今天我正在编写一个 AJAX 对象。
我创建了一个构造函数ajaxObj:
function ajaxObj( arg1, arg2, wrapper ) {
this.form = arg1;
this.btn = arg2;
this.msg = "Update successful";
this.url = "process.php";
this.wrap = wrapper; // this is the div the callback uses
this.serial = null; // serialized form for POSTing
this.callback = function () {
var div = document.createElement("div");
div.innerHTML = this.msg;
div.setAttribute( "id", "desiredID" );
this.wrap.appendChild(div);
}
this.btn.onclick = initXHR;
}
在给定页面上实例化了几个 ajaxObj 类型的对象。我想包含不会改变并且应该在原型上共享的功能:
ajaxObj.prototype = {
constructor: ajaxObj,
makeXHR: function () {
// cross browser XHR code returns XHR obj
}
makeSer: function () {
this.serial = $(this.form).serialize();
}
initXHR: function () {
// this is where shit gets weird!
this.makeSer(); // makeSer function doesnt exit
var http = this.makeXHR(); // makeXHR doesn't exist
http.onreadystatechange = function () {
/* this function checked for
http.status / http.readyState
and attempted to call this.callback()
which of course didn't exist.
I also tried to change instance
properties here which did not work */
}
http.open( "POST", this.url, true ); /* this.url did not work
and had to be replaced
with "process.php" */
http.setRequestHeaders("Content-Type","application/x..."); // TL;DT
http.send( this.serial ) // <--- this works just fine???
}
在过去的一周里,我查看了许多类似的问题,并为此付出了很多时间和考虑。我的代码现在可以工作了,方法是从构造函数中取出回调,以及从原型中取出 makeXHR() 和 makeSer()并将它们全部放在全局范围内。
尽管我的代码可以正常工作,但令我懊恼的是,我仍然不明白为什么this.url在xhr.open()中不起作用,而 this.serial在xhr.send()中起作用
Bascally,为什么'this'在原型的某些地方有效(例如替换
ajaxObj.prototype = {
.............
initXHR: function () {
makeSer();
....
http.open( "POST", this.url, true );
....
http.send( this.serial );
....
}
和
ajaxObj.prototype = {
.............
initXHR: function () {
this.serial = $(this.form).serialize();
....
http.open( "POST", "process.php", true );
....
http.send(this.serial);
}
....请不要让我迷惑。我的印象是我已经弄清楚了。当我使用 var 关键字时,在构造函数中设置 that=this 似乎不起作用,并且显然(对于 javascript,事情并不总是那么明显)删除等于值的 var 关键字集是用最新的对象实例实例化的。