-1
function Chat() {
    // hander vent //
    // this.message_text.on("keyup click", this.saveMessage);
    $('.chat').on("click", this.init);
}

Chat.prototype.init = function() {
    var sef = this;
    this.hihi();
}
Chat.prototype.hihi = function() {
    return 2;
}

let chat = new Chat();

I have two methods define in class type prototype. but when I call function name hihi inside function init. when I run code single with create instance with type Chat. it can't run and show error.

TypeError: this.hihi is not a function at HTMLButtonElement.Chat.init (fotozidiqo.js:9:10)

How I can call this function in init function name.

Ignacio Ara
  • 2,476
  • 2
  • 26
  • 37
tomnyson
  • 189
  • 2
  • 7

1 Answers1

-1

When doing this: $('.chat').on("click", this.init);, jQuery changes the this of the init() method to the element returned from $('.chat'). That's why it's undefined when you call this.hihi(); within the init method, because it doesn't exists on HTMLElement.

So in order to get the proper this you have to bind the this of the Chat prototype like so:

function Chat() {
    $('.chat').on("click", this.init.bind(this));
}

If you want to debug this, you can console.log(this) on your init() method and you'll see a HTMLElement.

lenilsondc
  • 9,590
  • 2
  • 25
  • 40