2

I have this simple class :

class myCustomClass{

    foo(value){
        //do some stuff
    }

    faa(){
        //do some stuff
        $.getJSON( someUrl, function(data) {
            // how call the method foo(value) here ?
            this.foo('fii'); // error occured here, because 'this' is not in 'class' context        
        }
    }
}

How can I use the method 'foo(value)' in the method faa when I use an AJAX statement ? I can't use a simply 'this.foo(value)' here because the context of 'this' in the AJAX statement isn't the 'class' context (but the AJAX context)

1
  • Coming from c# I think you need to instantiate the class inside the ajax call and then use it. Commented Nov 14, 2018 at 16:25

2 Answers 2

5

You need to 'cache' the reference to the class in the outer scope so it can be used in the inner scope of your AJAX callback, like this:

faa() {
  var _class = this; // cache class reference here

  // do some stuff

  $.getJSON(someUrl, function(data) {
    _class.foo('fii'); // use it here
  });
}

Alternatively you can use an arrow function, assuming you never need to use the inner scope of the callback:

faa() {
  // do some stuff

  $.getJSON(someUrl, (data) => {
    this.foo('fii'); // use it here
  });
}
Sign up to request clarification or add additional context in comments.

Comments

1

I usually do it in this way,

class myCustomClass {

    foo(value) {
        // do some stuff
    }

    faa() {
        var me = this;
        // do some stuff
        $.getJSON(someUrl, function(data) {
            // how call the method foo(value) here ?
            me.foo('fii'); // error occured here, because 'this' is not in 'class' context        
        });
    }
}

1 Comment

sorry, a little bit late, duplicate

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.