Reputation: 22440
I have a TypeScript class with a constructor. My goal is to change the "bar" property value by invoking the "baz" method inside the constructor. But, the baz method seems to have no effect. After the baz method is invoked, I'm expecting the bar property value to be "blue". Instead, the value remains "red".
class Foo {
bar:string = "red";
baz():void {
this.bar = "blue";
};
constructor() {
var bar = this.bar;
var baz = this.baz;
baz();
console.log(bar) // logs "red";
}
}
var x = new Foo();
Upvotes: 0
Views: 384
Reputation: 1710
The problem is that you are printing a local copy of bar
. It is assigned to "red". After calling baz
, then this.bar
should be "blue" but the local bar
is still "red".
Try this:
constructor() {
// var bar = this.bar; // unnecessary
// var baz = this.baz; // unnecessary
this.baz();
console.log(this.bar) // should be "blue";
}
Upvotes: 3
Reputation: 20063
There's actually two problems going on here:
this.baz
isn't bound correctly.Let's tackle #2 first. Basically, you're doing this:
let value = "red";
let bar = value;
value = "blue";
console.log(bar); // logs red
It's pretty obvious why it would not log blue instead since you reassigned the reference. This doesn't »propagate« to bar
. The same happens in your code:
var bar = this.bar;
// … reassign this.bar, but not bar
console.log(bar); // will not log the updated value
The second problem is that you need to use
var baz = this.baz.bind(this);
in order to get the context right (or just call this.baz()
directly).
Upvotes: 4