【问题标题】:javascript ES6 class/method scope [duplicate]javascript ES6类/方法范围[重复]
【发布时间】:2016-07-11 00:40:57
【问题描述】:

我不知道如何更正我的方法的上下文。

我有这门课:

export default class Handler {

    constructor() {
        // init
    }

    handleMessage(channel, user, message) {
        this.handleDefault(channel, user, message);
    }

    handleDefault(chanenl, user, message) {
        // do stuff
    }
}

被这个方法和类调用

export default class Bot {

    constructor() {
        this.irc     = irc // has an event emitter irc.event
        this.handler = new Handler();
        this.readIRC();
    }

    readIRC() {
        this.irc.event.on('message', this.handler.handleMessage);
    }
}

问题在于 handleMessage 中的第一个类,这不再是类而是 eventEmitter,所以我不能调用我的 handleDefault 方法。

如何在 ES6 中正确处理上下文?

【问题讨论】:

  • 您似乎在询问 this 上下文,而不是 范围

标签: javascript ecmascript-6 scopes


【解决方案1】:

您只需将handleMessage 绑定到this.handler,或者使用

  • Function.prototype.bind

    this.irc.event.on('message', this.handler.handleMessage.bind(this.handler));
    
  • 或使用箭头函数,

    this.irc.event.on('message', () => this.handler.handleMessage());
    

在这两种情况下,当在message 事件上调用handleMessage 函数时,handleMessage 中的this 将引用this.handle 对象。


如果你喜欢将参数传递给事件处理程序,你可以像这样定义箭头函数

this.irc.event.on('message', (err, msg) => this.handler.handleMessage(err, msg));

【讨论】:

  • 如果我使用箭头函数如何正确传递参数。
  • @danielps1:与handleMessage 本身的做法相同:定义参数并传递它们。或者使用 rest 参数和 spread 参数。
  • 哦,是的。我实际上是正确的,只是有一个愚蠢的错字。谢谢!
  • @danielps1 就像菲利克斯解释的那样。我只是举了一个简单的例子。 PTAL。
猜你喜欢
  • 1970-01-01
  • 2015-08-19
  • 1970-01-01
  • 2013-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
相关资源
最近更新 更多