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', []]]);
最後,我解決了它,但你指出了問題。謝謝。 – Kaspi 2012-04-08 20:32:04