2012-04-08 118 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