joh04667 joh04667 - 1 month ago 6
Node.js Question

How to refer to constructor methods when calling a function as an object property

More questions about prototype inheritance, fun fun. I am making a Slack bot and am trying to keep my code neat and tidy. I have made a constructor for the bot to handle all needed methods and properties.

I was going to make an object on the prototype that held a bunch of functions related to a specific functional area (responding to chat commands). The problem is, I still need to refer to functions on the prototype from within these methods...I dunno how to do that:

// generic function I put on prototype
SmashBot.prototype.postMessage = function() {
'do stuff'
}

// helper object full of functions I need
SmashBot.prototype.commands = {

tournament: function(message) {
this.postMessage('stuff'); // Method on SmashBot Prototype i need to use
console.log(this) // refers to this object (Smashbot.commands)
},

self: (message) => {
this.createTourney('stuff') // another method on prototype
console.log(this); // lexical arrow function makes 'this' just refer to '{}', not the constructor
}
}


and then from another function on the prototype:

this.commands.tournament()
// <--- this.postMessage() is not a function


So my question is....is there any neat way to put a bunch of functions in an object in order to use them, or do they all have to be directly on the prototype themselves? I tried putting them in the constructor, but same thing happened.

Thanks in advance.

Answer

Or you can do in this way

SmashBot.prototype.commands = function(){
let self = this;
return {
    tournament: function (message) {
        self.postMessage('stuff');     // Method on SmashBot Prototype i need to use
        console.log(this)     // refers to this object (Smashbot.commands)
    },
    self: (message) => {
        self.createTourney('stuff')   // another method on prototype
        console.log(this);   // lexical arrow function makes 'this' just refer to '{}', not the constructor
    }
}

};

And call it

this.commands().tournament('message')