0

I have two classes which are not related:

class A {
    myVar = null;

    myFunc() {
        console.log(this.myVar)
    }
}

class B {
    constructor(func){
        this.func = func;
    }

    callFunc() {
        this.func();
    }
}

My problem is the following:

let a = new A();
let b = new B(a.myFunc);
b.callFunc();

This will be undefined because this in console.log(this.myVar) won't refer to the instance of class A, but the instance of class B. How can I access the global variable of class A when calling the function from another class?

Ardweaden
  • 857
  • 9
  • 23
  • Either use `this.func.call(a)` in `callFunc`, or pass `() => a.myFunc()` as the argument to it. – Bergi Dec 27 '19 at 14:41

1 Answers1

3

You could use a.myFunc.bind(a), specifying that you want myFunc's this to refer to the a instance.

The bind() method creates a new function that, when called, has its this keyword set to the provided value

Also, don't forget your new operators :)

class A {
    myVar = "Hello world";
    myFunc() { console.log(this.myVar) }
}

class B {
    constructor(func){ this.func = func; }
    callFunc() { this.func(); }
}

let a = new A();
let b = new B(a.myFunc.bind(a));
b.callFunc();
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • Fantastic! This worked. Thanks for the reminder as well, I will edit the question - it's just a simplified example. – Ardweaden Dec 27 '19 at 14:46