Javascript - "this"为空

标签 javascript object scope

我正在尝试使用 Node.js 为我的 Web 应用程序编写服务器端。提取以下代码以模拟情况。问题是应用程序在尝试访问 actionExecuted“方法”中的 this.actions.length 时崩溃。属性 this.actions 在那里未定义(范围内的 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', []]]);

最佳答案

问题在于您定义回调的方式。它稍后被调用,因此它失去了上下文。您必须创建闭包或正确绑定(bind) this。创建闭包:

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

绑定(bind)到this:

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

两者都可以。

关于Javascript - "this"为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10065212/

相关文章:

javascript - 在 Node (node.js)中有效地从 Buffer 到 Buffer 进行 Base64 解码

java - 如何访问 TreeMap 中的特定元素?

javascript - 在 DOMContentLoaded 上的 javascript 函数中声明全局常量

javascript - 如何用async/await进行一一异步调用?

javascript - 将对象转换为数组

javascript - jquery 自动完成 : how to handle special characters (& and ')?

perl - 我应该如何在 Perl 中维护我的对象模块?

objective-c - 在 RestKit 中放置对象映射的最佳位置在哪里

java - 在java中使用超出范围的变量

JavaScript 范围和对象