このことはほとんど機能します:
function myClass(url) {
this.source = url;
this.rq = null;
this.someOtherProperty = "hello";
// open connection to the ajax server
this.start = function() {
if (window.XMLHttpRequest) {
this.rq = new XMLHttpRequest();
if (this.rq.overrideMimeType)
this.rq.overrideMimeType("text/xml");
} else
this.rq = new ActiveXObject("Microsoft.XMLHTTP");
try {
this.rq.onreadystatechange = connectionEvent;
this.rq.open("GET", this.source, true);
this.rq.send(null);
this.state = 1;
} catch (err) {
// some error handler here
}
}
function connectionEvent() {
alert("i'm here");
alert("this doesnt work: " + this.someOtherProperty);
}
} // 私のクラス
つまり、XMLHttpRequestオブジェクトをグローバルに定義するのではなく、クラスのメンバーとして持ち、従来の方法で呼び出すことに他なりません。ただし、connectionEventコールバック関数内では、関数自体がmyClass内でスコープされていても、「this」の意味は失われます。また、myClassからインスタンス化するオブジェクトが十分に長く存続していることを確認しました(スクリプトでグローバルに宣言されています)。
私が見たjavascriptクラスの使用例ではすべて、「this」は内部関数内で引き続き使用可能でした。私にとっては、関数を外部に持ち出してmyClass.prototype.connectionEventにしたとしても、そうではありません。私は何が間違っているのですか?ありがとうございました。