-2

hi i have a problem with es6 and in particulary the methods of class. See my exemple :

my first class :

class A{
    constructor(){
         this.B = new B();
         this.test = 5;
    }
    methodA1(){
         B.methodB1(this.methodA2);
    }
    methodA2(){
         console.log(this.test);
    }
}

the second class :

class B{
    methodB1(callback){
         $.get("url",function(data){
              ...
              callback();
         });
    }
}

When you execute methodA1, the code return : this is undefined (in a methodeA2) ! In fact when you call a callback function in ajax call the callback lost the context of class. Somebody have an idea to skirt this problem ?

Thanks.

Freddy
  • 137
  • 8
  • This is the nature of asynchronous operations. Look into promises. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) – Scott Marcus Feb 03 '17 at 18:37

2 Answers2

2

You can use .bind to bind this.

methodA1(){
    this.B.methodB1(this.methodA2.bind(this));
}
Diego Faria
  • 8,805
  • 3
  • 26
  • 33
1

You get an error because you are not correctly referencing the B property you created in your constructor.

If you are sure that you'll be invoking methodA1 in the context of class A, then you can refer to property B by this.B. The this conext would point to the reference of the class A where B exists:

class A{
    constructor(){
         this.B = new B();
         this.test = 5;
         this.methodA2 = this.methodA2.bind(this);
         // I prefer to bind my methods in the constructor so they are bound once
    }
    methodA1(){
       this.B.methodB1(this.methodA2);
//     ^ -- the B property created in constructor B exists as a property 
//          of this class, to reference it within a class method you need 
//          to call this.B
    }
    methodA2(){
         console.log(this.test);
    }
}

class B{
    methodB1(callback){
         $.get("url",function(data){
              ...
              callback();
         });
    }
}

const a = new A();
a.methodA1();  // will log out 5 when the `$.get` request has its callback invoked
Pineda
  • 7,435
  • 3
  • 30
  • 45