0

I have this situation

class A {
  a(params) {
    //some code here
  }

  b(params) {
    //some code here
  }

  c(params) {
    this.a(function(data) {
      console.log(this);    // undefined
      this.b();             // error no function b of undefined
    }) 
  }
}

I have tried binding this to 'a' using bind(this) but it says Cannot read property 'bind' of undefined or this is not defined. When I print this, I get class A. I want to call it inside 'a' function.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
user169772
  • 31
  • 5

2 Answers2

5

When you have defined a new function, the meaning of this has been changed inside it. You either need to use an arrow function:

this.a((data) => {
  console.log(this); // class A
  this.b();
})

or save the reference of this in a local variable:

var self = this;

this.a(function(data){
  console.log(self); // class A
  self.b();
})
31piy
  • 23,323
  • 6
  • 47
  • 67
  • 1
    You can also use `bind` to set the value of `this` on a `function`. – sjahan May 03 '18 at 07:26
  • I will rather suggest to simplify the code if OP is the author. – 31piy May 03 '18 at 07:27
  • Great answer. Arrow functions are the best way to go. The version with `self` is pre-2015 but you will see it if you care to look at the output of transpilers like Babel. I don't understand the comment about using `bind`..., @sjahan, in the inner function, you've already lost the `this` reference to the A object. How do you propose to get it back? – Ray Toal May 03 '18 at 07:35
  • @RayToal this work right? `this.a((function(data) { console.log(this); this.b(); }).bind(this));` Not the coolest way syntaxically speaking, but it's always good to know every way you can do this! Also, watchout, sometimes, you cannot use arrow functions instead of functions, in arrow functions, there is no access to `arguments` for example! – sjahan May 03 '18 at 07:44
  • Ah yes, very nice! `bind` on the very outside! I didn't see that. :) – Ray Toal May 03 '18 at 07:45
-1

Not sure at which point you are expecting the "b" method execution. I've added jsFiddle here: https://jsfiddle.net/k3jkobae/ and just saw that there was short correct answer while I was wrapping mine :) The arrow function is best suited.

class A {
    a( callback ){
        console.log('a');
        callback();
    }

    b(params){
         console.log('b');
     }

    c(params) {
       this.a( () => this.b() ); 
    }
}

const myClass = new A();
myClass.c();
Miroslav Savovski
  • 2,300
  • 2
  • 10
  • 12