Reputation: 495
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.
Upvotes: 1
Views: 40
Reputation: 1275
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();
Upvotes: 1
Reputation: 16908
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();
Upvotes: 3