0

I am trying to implement a Singleton in my class, but somehow this does not exist when I call the funcA function. One of my first calls in my Software is a call to the funcB function. Here everything works fine, I receive the content I intended to get. Later I try to call it from a different class again, but this time the funcA function. Now I get the Error I wrote down below. Why does it work when I call it in one file but not in a different?

export class Singelton {
  private static _instance: Singelton;
  private _service: Service;
  private obj: Object;

  private constructor() {
    this.obj = null;
    this._service = new Service();
  }

  public static getInstance(): Singelton {
    if (!Singelton._instance) {
      Singelton._instance = new Singelton();
    }
    return Singelton._instance;
  }

  public funcA(data: Data): void {
    this._service.someLogic(...)
  }

  public funcB(): Object | null {
    return this.obj;
  }
}

This is the Error message:

ERROR TypeError: Cannot read properties of undefined (reading '_service') (from funcA)
Chrissi
  • 15
  • 8
  • 1
    *How* do you call `funcA`? – VLAZ Apr 03 '23 at 18:12
  • `import {Singelton} from "./Singelton.js"; const a = Singelton.getInstance(); someDifferentFunc(a.funcA)` and in the other file `cb(data)` – Chrissi Apr 03 '23 at 18:25
  • Does this answer your question? [TypeScript "this" scoping issue when called in jquery callback](https://stackoverflow.com/questions/20627138/typescript-this-scoping-issue-when-called-in-jquery-callback) also [How to access the correct `this` inside a callback](https://stackoverflow.com/q/20279484) `omeDifferentFunc(a.funcA)` -> `omeDifferentFunc(() => a.funcA())` – VLAZ Apr 03 '23 at 18:26
  • Yes it does! Thank you! Funny thing is I looked at this article and tried it, but I think I changed it at the wrong position, but now it works, thank you! – Chrissi Apr 03 '23 at 18:35

0 Answers0