2012-04-08 6 views
1

Node.jsを使用してWebアプリケーション用のサーバーサイドを作成しようとしています。次のコードは、状況をシミュレートするために抽出されます。問題は、actionExecutedの「メソッド」のthis.actions.lengthにアクセスしようとすると、アプリケーションがクラッシュすることです。 this.actionsプロパティは、 "コンストラクタ"(Request関数自体)で定義されていても、そこでは定義されていません(この範囲内の== {})。アクションプロパティを他の「メソッド」からもアクセス可能にするにはどうすればよいですか?Javascript - "this"が空です

var occ = { 
    exampleAction: function(args, cl, cb) 
    { 
     // ... 

     cb('exampleAction', ['some', 'results']); 
    }, 

    respond: function() 
    { 
     console.log('Successfully handled actions.'); 
    } 
}; 

Request = function(cl, acts) 
{ 
    this.client = cl; 
    this.actions = []; 
    this.responses = []; 

    // distribute actions 
    for (var i in acts) 
    { 
     if (acts[i][1].error == undefined) 
     { 
      this.actions.push(acts[i]); 
      occ[acts[i][0]](acts[i][1], this.client, this.actionExecuted); 
     } 
     else 
      // such an action already containing error is already handled, 
      // so let's pass it directly to the responses 
      this.responses.push(acts[i]); 
    } 
} 

Request.prototype.checkExecutionStatus = function() 
{ 
    // if all actions are handled, send data to the client 
    if (this.actions == []) 
     occ.respond(client, data, stat, this); 
}; 

Request.prototype.actionExecuted = function(action, results) 
{ 
    // remove action from this.actions 
    for (var i = 0; i < this.actions.length; ++i) 
     if (this.actions[i][0] == action) 
      this.actions.splice(i, 1); 

    // and move it to responses 
    this.responses.push([action, results]); 
    this.checkExecutionStatus(); 
}; 

occ.Request = Request; 

new occ.Request({}, [['exampleAction', []]]); 

答えて

2

問題は、コールバックを定義する方法です。それは後で呼ばれ、文脈を失います。クロージャを作成するか、またはthisを正しくバインドする必要があります。

var self = this; 
occ[acts[i][0]](acts[i][1], this.client, function() { self.actionExecuted(); }); 

thisにバインドする:

occ[acts[i][0]](acts[i][1], this.client, this.actionExecuted.bind(this)); 

いずれかが動作するはずクロージャを作成します。

+0

最後に私はそれを解決しましたが、あなたは問題を指摘しました。ありがとう。 – Kaspi

関連する問題