edt
edt

Reputation: 22440

What is the proper way to reference TypeScript class methods and properties from the constructor?

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

Answers (2)

djs
djs

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

Ingo Bürk
Ingo Bürk

Reputation: 20063

There's actually two problems going on here:

  1. Your reference to this.baz isn't bound correctly.
  2. You're logging an object you »copied« before you called the method.

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

Related Questions