今日は 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???
}
この 1 週間、多くの同様の質問に目を通し、これについて十分な時間をかけて検討してきました。コンストラクターからコールバックを取り出し、プロトタイプから makeXHR() と makeSer() を取り出し、それらをすべてグローバル スコープに配置することで、コードが機能するようになりました。
コードが機能しているという事実にもかかわらず、残念なことに、なぜthis.urlがxhr.open()内で機能しなかったのか、 this.serialは xhr.send ( )内で機能するのかまだわかりません。
基本的に、プロトタイプのいくつかの場所で「これ」が機能するのはなぜですか(置換など)
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 キーワード セットを削除すると、最新のオブジェクト インスタンスでインスタンス化されます。