Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting methods in ES6 classes?

I have been trying to follow a DRY programming and I have been repeating myself so I tried to nest methods within a parent method that help some code.

chat() {
  client.on("chat", (channel, user, message, self) => {

   method() {
     // code here
   }

   method() {
     // code here
   {

  }
}

But that didn't work out as expected calling class.chat.method() didn't bring back anything. What I really need help with is removing my DRY programming I call client.on("chat", callback()) every single method I use. Curious whether this can be prevented and have just one snippet with methods called within it.

FULL CODE:

watchFor(command, res, sendersName, prefix) {
    this.client.on("chat", (channel, user, message, self) => {
        console.log(this._showSendersName.whitelistedCommands);
        if (message == this.prefix + command || message == prefix + command) {
            return this.client.say(channel, res);
        }
    });
}
modOnly(command, res) {
    this.client.on("chat", (channel, user, message, self) => {
        if (this._showSendersName == false) {
            if (self) return
        }
        if (message == this.modPrefix + command && user.mod || message == this.prefix + command && user.mod) {
            return this.client.say(channel, res);
        } 
    });
} 
broadcasterOnly(command, res) {
    this.client.on("chat", (channel, user, message, self) => {
            if (this._showSendersName == false) {
                if (self) return
            }
            if (message == this.prefix + command && user.badges.broadcaster == 1) {
                return this.client.say(channel, res);
            }
    });
}   
like image 789
Ethan Moffat Avatar asked Sep 17 '26 04:09

Ethan Moffat


1 Answers

You can't use ES6 method definition shorthand outside of object initializers. Try declaring another function once inside function scope:

chat() {
  client.on("chat", (channel, user, message, self) => {

    const sharedMethod = () => {
      // code here
    }

    sharedMethod()
  })
}
like image 185
Chris Trombley Avatar answered Sep 18 '26 16:09

Chris Trombley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!