2012-04-08 58 views
1

我正在嘗試使用Node.js爲我的Web應用程序編寫服務器端。下面的代碼被提取以模擬情況。問題是當試圖訪問actionExecuted「方法」中的this.actions.length時,應用程序崩潰。屬性this.actions在該範圍內未定義(this == {}),即使它是在「構造函數」(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 2012-04-08 20:32:04