0

次のように、2 つのメソッドを持つオブジェクトがあります。

function PendingRequests(){
    this.count;
    this.id = [];
    this.event = [];
}
PendingRequests.prototype.get = function(){
    var request_parameter = 'cont=pr';
    Ajax(url,request_parameter,this.get2);
}
PendingRequests.prototype.get2 = function(pr){
    this.count = pr.length;
    for(var i=0;i<this.count;i++){
        this.id[i]          = pr[i]['id'];
        this.event[i]       = pr[i]['event'];
    }
}
var pendingrequests = new PendingRequests();

そしてajax関数

Ajax(url,parameter,funct){...}

応答を取得した後、渡された関数を呼び出します

funct(JSON.parse(XMLHttpRequestObject.responseText));

スクリプトは、ajax 応答後にメソッドを呼び出すまで実行されますが、「this.id is undefined」というエラーが表示されます

これを手伝ってください。

4

2 に答える 2

0

関数にコンテキストを割り当てる必要があります。そうしないと、グローバル コンテキストで呼び出されます。ajax 関数で別のパラメーターを受け入れる必要があります。

Ajax(url,parameter,funct, context){...}

次に、呼び出しを使用して関数をトリガーします。

funct.call(context, JSON.parse(XMLHttpRequestObject.responseText));

次に、get 関数の呼び出しは次のようになります。

Ajax(url,request_parameter,this.get2, this);
于 2012-12-12T08:15:29.790 に答える
0

ねえ、両方の提案を試しましたが、それでも同じエラーが発生しました。

最後に、私は問題を解決しました。

私はイアンが提案した変更を加えました。(ajax関数は他のオブジェクトも処理しますが、それらすべてに対してget2メソッドを定義できます)

それでもエラーが発生していたので、すべてのプロパティを定義しました:

this.count;
this.id = [];
this.event = [];

別の方法で:

PendingRequests.prototype.count = 0;
PendingRequests.prototype.id = [];
PendingRequests.prototype.event = [];

今は機能しています... PendingRequests オブジェクトは 1 つしかないので、後でプロトタイピングでエラーが発生しないことを願っています。

于 2012-12-12T18:21:23.570 に答える