Yoctol / bottender

⚡️ A framework for building conversational user interfaces.
https://bottender.js.org
MIT License
4.22k stars 335 forks source link

使用router進行功能分流,this參照值問題 #778

Closed hanshino closed 4 years ago

hanshino commented 4 years ago

先看以下code

const {text, router} = require('bottender/router') ;

class foo
{
    bar()
    {
        // doSomething
        console.log('in bar') ;
        this.test() ; // TypeError: Cannot read property 'test' of null
    }

    test()
    {
        // doSomething
        console.log('in test') ;
    }
}

const myClass = new foo ;

module.exports = async function App(context) {
    return router([
        text('bar', myClass.bar),
        text('*'  , myClass.test)
    ]) ;
};

最近開始學習使用bottender發現,上面foo.bar裡面在呼叫this.test() this參照值會是上一層的物件 我想這是因為arrow function的關係

我想問的是,是我流程上不該如此設計,又或者是我使用方式錯誤呢? 因為只有我有這問題,方便的話想請教你們都如何coding這類流程的function

English is not my native language. If needed, I will try to transalte this issue. Thanks.

jigsawye commented 4 years ago

Please have a look: https://stackoverflow.com/a/51881233

If you are not using Babel, try this below

class Foo {
  constructor() {
    this.test = this.test.bind(this);
  }

  bar() {
    // doSomething
    console.log('in bar') ;
    this.test();
  }

  test() {
    // doSomething
    console.log('in test') ;
  }
}
hanshino commented 4 years ago

Thanks for your reply. I will try it.