1

I am trying to call the same method within a method in a Javascript ES6 class but it is not working.

class Client {
    constructor(connection) {
        this.channels = [];
        this.nickname = null;
        this.user = null;
        this.realName = null;
        connection.on('data', this.parse_message);
    }
    parse_message(message) {
        let messageObject = {};
        if (message.includes('\r\n')) {
            message = message.split('\r\n');
            message.forEach((el) => {
                this.parse_message(el); 
            });
        }
        else {
            message = message.split(' ');
            console.log('Message Received: ', JSON.stringify(message));
        }
    }
} 

When ran I get this error TypeError: this.parse_message is not a function. I tried assigning this to a variable self at the top but that still didn't work.

Isiah L
  • 443
  • 5
  • 20
  • Please show how you call this function / create a new object from the class. And what is connection? – Sébastien Mar 11 '18 at 20:09
  • @Sébastien I'm sorry if I'm not understanding correctly but the parse_message method is being called in the constructor at ` connection.on('data', this.parse_message);` The Client class is being created in a separate class if you think I should post that? – Isiah L Mar 11 '18 at 20:12
  • No need I think @doodlemeister has the right idea. – Sébastien Mar 11 '18 at 20:18

2 Answers2

2

Pass an arrow function as the bound handler so that you can keep this associated with the method.

    connection.on('data', (...args) => this.parse_message(...args));

Now your this in the forEach callback will be the expected value.

  • Thank you! If you don't mind explaining the (...args) part to me that would be awesome. I'm a bit of an ES6 noob. – Isiah L Mar 11 '18 at 20:23
  • @IsiahL: Sure, in the function parameter position, it's just a way of collecting all the arguments from that point forward. So it's called a "rest" parameter, because it gives you an array of the rest of the arguments passed. At the call site, it does the opposite; it *passes* the Array of arguments to the function being called, but passes them as individual args instead of a collection. It's called "spread" syntax because it "spreads out" the content of the Array into the function being called. –  Mar 11 '18 at 20:42
0

You can use bind in the constructor:

this.parse_message = this.parse_message.bind(this); 

Bind-ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Matt
  • 141
  • 9