关键字“this”进入eventHandler函数,运行到类中

时间:2016-06-26 13:17:07

标签: javascript node.js ecmascript-6

我正在创建一个Telegram bot并尝试为它实现类似模块的架构。因此,为了处理内联查询,我创建了该类:

class inlineVacationsHandler {
    constructor(bot){
        this.bot = bot;
        this.bot.on('inline_query',this.handler);
    }


    handler(msg){
       console.log(this.bot);
    }
}


var bot = new TelegramBot(config.token_dev, {polling: true});

var inline = new inlineVacationsHandler(bot);

但问题是,我不能在eventHandler中使用类字段“bot”,因为在这种情况下“this”不指向inlineVacationsHandler类。那么,我如何从hadler函数中获取“bot”对象?谢谢。我正在使用Node.js和ES2016。

1 个答案:

答案 0 :(得分:1)

class inlineVacationsHandler {
    constructor(bot){
        this.bot = bot;
        this.bot.on('inline_query',this.handler.bind(this));
    }


    handler(msg){
       console.log(this.bot);
    }
}


var bot = new TelegramBot(config.token_dev, {polling: true});

var inline = new inlineVacationsHandler(bot);
  
    

使用this.bot.on(' inline_query',this.handler.bind(this));

  
相关问题