0

I'm pretty new with javascript and I think this is a dumb question but I don't know how to search my issue on google.

I have a "class" like that :

function Myclass(){}

Myclass.prototype.method1() = function(){

    whatever.onload = function(){
      this.method2();
    }

};

Myclass.prototype.method2() = function(){};

My problem is that "this" isn't related to my class anymore. In this anonymous function scope, I can't reach my method2.

How can I solve this issue ?

Thanks for your advices.

1 Answer 1

4

The simplest way is like this:

Myclass.prototype.method1 = function(){
    var self = this;
    whatever.onload = function(){
      self.method2();
    }
};

The variable self remains in existence even after method1 finishes executing such that the onload function declared with method1 can still access it later. (For more information about this, google "JavaScript closures".)

Sign up to request clarification or add additional context in comments.

2 Comments

I think you meant Myclass.prototype.method1 = function(){ in your first line of code. Looks like a typo.
@Reno - Yep. I had copied that line directly from the question and didn't notice the problem. Fixed.

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.