Luis González
Luis González

Reputation: 3559

Calling javascript class methods from another method inside the same class

I don't know how to deal properly with this case. I have a Javascript object like this:

var myClass = {

    init : function(){
        $("button").on("click" , this.func1);
    },

    func1: function(){

        // do stuffs

        this.func2();

    },

    func2: function(){

        // do stuffs
    }
}

myClass.init();

When I initialize my class for binding event there's no problem. In the init function, the value of this is the class itself, so I can call their methods without problem.

Take into account that when a button is clicked, I executed func1. I found the problem inside the function func1 because in this case the value of this is the button that was pressed, so when I try this.func2 I get Uncaught TypeError: this.func2 is not a function.

How I deal with this kind of problem? I'm sure that there is a standar way to solve this problem but I don't know it.

Thanks !!

Upvotes: 1

Views: 302

Answers (1)

Lewis
Lewis

Reputation: 14866

From your example, this.func1 is actually bound to no context when it is executed. So its this keyword will be either fallbacked to window object on legacy mode or undefined on strict mode. In order to execute this.func1 in myClass context, you can use one of these methods:

  1. Set this to myClass with Function.prototype.bind

    $("button").on("click", this.func1.bind(this));
    
  2. Wrap inside an anonymous function

    var self = this;
    $("button").on("click", function() {
      self.func1();
    });
    
  3. Wrap inside an arrow function

    $("button").on("click", () => this.func1());
    

Upvotes: 4

Related Questions