0

I am confused about this when calling a function from an object literal.

module.exports = {
    name: 'quiz',
    owner: '',
    numOfQuestions: 0,
    difficulty: '',
    channel: {},

    execute: async function (args, msg) {
        this.channel = msg.channel.id;
        this.owner = msg.author.id;
        this.channel = msg.channel;

        // axios.get('https://opentdb.com/api.php?amount=1&category=15&difficulty=easy');
        console.log('Quiz started');
        console.log(this.name);



        this.channel.send('How many questions?').then(this.getNumOfQuestions);
    },

    getNumOfQuestions: function () {
        console.log(this.name);
        this.channel.awaitMessages(this.filterNumOfQuestions, { max: 1, time: 15000})
            .then(collected => {
                this.channel.send(`You asked for ${collected.first().content} questions.`);
            })
            .catch(collected => {
                this.channel.send('You did not tell me how many questions you wanted. Ending the quiz');
            });
    },

Another file requires this and calls the execute method. But this in the getNumOfQuestions function is not the instance of the object literal, this.name for example returns undefined. I am not sure why, please can someone explain this.

gclark18
  • 659
  • 6
  • 23
  • 1
    See the duplicate. Use `.then(this.getNumOfQuestions.bind(this))`. – Felix Kling Aug 15 '20 at 17:11
  • Okay, that resolved the issue. I do not understand why I need to use bind, when I call a function from within an object literal so I spawn a new instance? – gclark18 Aug 15 '20 at 17:16
  • You can assign this to a variable, which you would be able to access the main object you want. E.g `let that = this` – Fritzdultimate Aug 15 '20 at 17:25
  • 1
    The duplicate should explain it. What `this` refers to depends on how the function is called. `.then` will call it like a "normal" function, hence `this` will be `undefined`. If you create a bound function, `this` will always refer to what you bind it to. – Felix Kling Aug 16 '20 at 21:02
  • 2
    @Fritzdultimate: That only really works if you define the callback "inline" which is not the case here. – Felix Kling Aug 16 '20 at 21:02

0 Answers0