当单独调用函数时,可以在函数中调用对象的方法,但是当通过setTimeout调用函数时,对象是未定义的

时间:2019-02-09 07:57:58

标签: javascript node.js settimeout es6-class

我有以下课程Conference

//UrlSerializer is for encoding JSON objects into GET url
const UrlSerializer=require('./urlSerializer');

class Conference{

    constructor(client,workspace){
        this.client=client;
        this.workspace=workspace;
        this.urlSerializer=new UrlSerializer();
    }


    announce(conferenceSid,timeRemaining){
        var parameters={
            timeRemaining:timeRemaining
        }
        var url=this.urlSerializer.serialize('conferenceAnnounceTime',parameters);
        console.log("conference.announce url: "+url);
        this.client.conferences(conferenceSid)
            .update({
                announceUrl:url,
                announceMethod:'GET'
            })
            .then(conference=>console.log(conference.friendlyName));
    }

    setTimedAnnounce(initialMinutes,minutesToElapse,conferenceSid){
        var minutesRemaining=initialMinutes-minutesToElapse;
        setTimeout(this.announce,minutesToElapse*60000,minutesRemaining);
    }

}

module.exports=Conference;

UrlSerializer是:

const querystring=require('querystring');
require('env2')('.env');

class UrlSerializer{

    constructor(){
        this.paramArrayName="parameters";
    }

    serialize(endpoint,paramArray){
        var url=process.env.APP_BASE_URL+"/"+endpoint;
        console.log("urlSerializer base url: "+url);
        var arrayString=JSON.stringify(paramArray);
        console.log("urlSerializer stringified parameter array: "+arrayString);
        var fullUrl=url+"?"+querystring.stringify({[this.paramArrayName]:arrayString});
        console.log("urlSerializer full url: "+fullUrl);
        return fullUrl;
    }   
}

module.exports=UrlSerializer;

我从另一个模块conference中的Express端点调用server函数,如下所示:

app.get('/conferenceEvents',function(req,res){
    conferenceSid=req.query.ConferenceSid;
    conference.announce(conferenceSid,initialMinutes);
    conference.setTimedAnnounce(initialMinutes,0.25,conferenceSid);
    res.type('application/json');
    res.status(200).send();
});

conference.announce的调用通过控制台输出成功:

urlSerializer base url: http://x.ngrok.io/conferenceAnnounceTime
urlSerializer stringified parameter array: {"timeRemaining":5}
urlSerializer full url: http://x.ngrok.io/conferenceAnnounceTime?parameters=%7B%22timeRemaining%22%3A5%7D
conference.announce url: http://x.ngrok.io/conferenceAnnounceTime?parameters=%7B%22timeRemaining%22%3A5%7D

但是在调用conference.setTimedAnnounce()后经过15秒时,出现以下错误:

TypeError: Cannot read property 'serialize' of undefined
    at Timeout.announce [as _onTimeout] (c:\thisAppPath\conference.js:45:30)
    at ontimeout (timers.js:502:15)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)

我在想,也许当计时器调用announce时,它是在urlSerializer实例超出范围的情况下这样做的。通过urlSerializer调用announce时如何识别setTimeout()

编辑:我尝试如下保存this范围:

    setTimedAnnounce(initialMinutes,minutesToElapse,conferenceSid){
        var that=this;
        var minutesRemaining=initialMinutes-minutesToElapse;
        setTimeout(that.announce,minutesToElapse*60000,minutesRemaining);
    }

但是那给了我同样的错误。

编辑2:

我使用了Barmar的this.announce.bind(this)解决方案,并且解决了TypeError,但是在宣布的setTimeout()调用中没有正确构造参数数组和URL。控制台输出如下:

urlSerializer base url: http://x.ngrok.io/conferenceAnnounceTime
urlSerializer stringified parameter array: {}
urlSerializer full url: http://x.ngrok.io/conferenceAnnounceTime?parameters=%7B%7D
conference.announce url: http://x.ngrok.io/conferenceAnnounceTime?parameters=%7B%7D

我怀疑还有其他地方需要使用.bind(this),以便在适当范围内使用urlSerializer.serialize()来调用this,但我还没有找到它。

编辑3:

没关系,我想通了-setTimeoutconferenceSid一样需要传递minutesRemaining作为参数。现在工作。

1 个答案:

答案 0 :(得分:1)

    setTimeout(this.announce,minutesToElapse*60000,minutesRemaining);

需要成为

    setTimeout(this.announce.bind(this),minutesToElapse*60000,minutesRemaining);

将函数属性作为参数传递不会绑定this上下文。仅当您使用该语法调用方法时,它才会自动绑定。