Javascript - "this" is empty
Javascript - "this" is empty
我正在尝试使用 Node.js 为我的 Web 应用程序编写服务器端。提取以下代码以模拟情况。问题是应用程序在尝试访问 actionExecute "方法" 中的 this.actions.length 时崩溃。属性 this.actions 在那里是未定义的(这个 == {} 在范围内),即使它是在"构造函数"(请求函数本身)中定义的。如何使动作属性也可以从其他"方法"访问?
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', []]]);
问题在于您定义回调的方式。稍后调用它,因此会丢失上下文。您必须创建闭包或正确绑定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));
任何一个都应该工作。
相关文章:
- 铬:“;未捕获的语法错误:意外的标记:"
- 可以设置“;文件名"发生错误时显示的内联脚本标记的
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- 使用“+="操作人员
- //而不是在src=“”上使用http://"属性
- "未捕获的语法错误:意外的标记}"
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- "实例范围”;TypeScript类的getter/setter
- Javascript复选框函数:;缺少:在属性id之后"
- "“;变量未引用正确的对象
- "日期“;AJAX请求返回的类型值未定义
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- "工具提示"jQuery插件坏了
- "锻造;React中的表达式
- 图像可以从源<img src=""/>.TEXT可以在没有javascript的情况下从外部
- 如何提取“;href"最近列表项中的属性值
- CKEditor如何允许href="javascript:void(0)"在小部件中
- 插入“;img src"在javascript中