无法在 setInterval 中读取 属性

Cannot read property in setInterval

在 node.js 我得到一个错误:

TypeError: Cannot read property 'talk_duration' of undefined

发件人:setTimeout(this.hangup, this.data.talk_duration * 1000);setInterval.

但是,在 setInterval 之外,我有 console.log(this.data.talk_duration); 可以正常工作。

this.outcomeAnswer = function () {

    console.log(this.data.talk_duration); //this work

    num = 0;

    db.run("INSERT INTO in_queue (action_id, state) VALUES ('" + this.data.action_id + "', 'InQueue')", function (error) {
        queueCheckLoop = setInterval(function () {

            num++;

            if (num == 5) {
                clearInterval(queueCheckLoop);
            }

            db.each("SELECT count(*) as total FROM agent_queue WHERE state = 'Ready'", function (err, row) {
                if (row.total > 0) {
                    clearInterval(queueCheckLoop);
                    setTimeout(this.hangup, this.data.talk_duration * 1000);
                }
            });
        }, 1000);
    });
}

您需要记住 this 作为 oucomeAnswer 函数的第一行,例如: var that=this;

然后使用 that.data.talk_duration 在具有不同作用域的函数中。