无法读取setInterval中的属性

时间:2015-08-25 15:20:55

标签: javascript node.js this 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);
    });
}

1 个答案:

答案 0 :(得分:2)

你需要记住this作为你的oucomeAnswer函数的顶线,例如: var that=this;

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