1

I can call class function from initiated class, but i cant display value of class property.

class A {
  constructor() {
    this.myvariable = "value";
    let b = new B(this.myCallback);
  }

  myCallback() {
    console.log(`myCallback() => ${this.myvariable}`);
  }
}

class B {
  constructor(cb) {
    cb();
  }
}

var a = new A();

I need to call class A method from class B. When I do as above, console prints this.myvariable as undefined.

2 Answers 2

3

That is happening as the myCallback is losing its context, you need to bind the myCallback to the context of the class A instance explicitly.

Without the context inside myCallback, this.myvariable would be undefined:

class A {
  constructor() {
    this.myvariable = "value";
    let b = new B(this.myCallback.bind(this));
  }

  myCallback() {
    console.log(`myCallback() => ${this.myvariable}`);
  }
}

class B {
  constructor(cb) {
    cb();
  }
}

var a = new A();

Sign up to request clarification or add additional context in comments.

Comments

1

As the other answer has explained what is really happening clearly, here just provide an alternative to achieve that, since Arrow functions do not bind their own this, instead, they inherit the one from the parent scope, we can also do it like so:

class A {
  constructor() {
    this.myvariable = "value";
    let b = new B(this.myCallback);
  }

  myCallback = () => {
    console.log(`myCallback() => ${this.myvariable}`);
  }
}

class B {
  constructor(cb) {
    cb();
  }
}

var a = new A();

but using arrow function as class member is an experimental feature, so for better compatibility:

class A {
  constructor() {
    this.myvariable = "value";
    let b = new B(() => this.myCallback());
  }

  myCallback(){
    console.log(`myCallback() => ${this.myvariable}`);
  }
}

class B {
  constructor(cb) {
    cb();
  }
}

var a = new A();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.