-1
export class Http {

     m1(s:string) {
       console.log("in m1",s);
     }

     m2(s:string) {
       console.log("in m2",s);
     }

}

export class a{

     http=new Http();

     op(s:string) {
        console.log(this);
        this.http.m1(s+"from a");
     }

}

export class b {

      http=new Http();

      constructor() { }

      op1(s:string) {
        console.log(this);
        this.http.m2(s+"from b");
      }

}

//main function call
let v = 2
let ptr = null;
let a1 = new a();
let b1 = new b();

switch(v) {
    case 1:
      ptr=a1.op;
      break;

    case 2:
      ptr=b1.op1;
      break;
}

ptr("s");

here in the above example, I have created a & b class has op & op1 method respectively. on the basis of my choice(like in switch statement) I want to call a method. but I get an error 'Cannot read property 'http' of undefined'. Can anyone explain why this is happening?

Thanks in advance!!

Guerric P
  • 20,579
  • 2
  • 28
  • 66
ganesh marmat
  • 144
  • 1
  • 4

1 Answers1

0

That's because doing ptr = a1.op; ptr("s"); is fundamentally different from doing a1.ptr("s");

this value depends from where you call the function. In case you call ptr("s"), it's an equivalent of window.ptr("s") so this is window in sloppy mode, undefined in strict mode (for more details on strict and sloppy modes, please read the MDN docs)

When you call the function from an object, this is the object that's why a1.op("s") will work because this will be a1

Guerric P
  • 20,579
  • 2
  • 28
  • 66
  • 2
    Trying to put it more succinctly: the value of `this` is decided at *calltime* and will be set to the thing before the `.`. In `a.b()`, `this` inside `b` will be `a`. No `a.`, no `this`. – deceze Jun 11 '20 at 14:37