1

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 !!

4

1 Answer 1

4

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());
    
Sign up to request clarification or add additional context in comments.

13 Comments

should I change something inside the func1 implementation?
@LuisGonzález no, you just need to bind it here. He did not explain it, that's the problem.
Thank you so much! Your answer fixed magically the bug. I didn't know about the bind function!
@LuisGonzález you might want to have a look at the first answer in the doublicate link. It has some nice additional Infromation about all that
@LuisGonzález It's already described in the link. this.func1.bind(this,arg1,arg2,...)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.