spacecodeur
spacecodeur

Reputation: 2406

OOP javascript, from a AJAX 'statement' in a method, how call an another method of the class?

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)

Upvotes: 2

Views: 57

Answers (2)

Victor Xie
Victor Xie

Reputation: 148

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        
        });
    }
}

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337627

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
  });
}

Upvotes: 5

Related Questions