Skip to content

Instantly share code, notes, and snippets.

@johnlindquist
Last active March 17, 2016 19:33
Show Gist options
  • Save johnlindquist/7be8139cea11c5dd1042 to your computer and use it in GitHub Desktop.
Save johnlindquist/7be8139cea11c5dd1042 to your computer and use it in GitHub Desktop.
Opinion

Anyone have an opinion on this field assignment to this in classes?

export class App {
    foo = this.bar;
    
    constructor(public bar){
    }
}

it compiles to the same thing as:

export class App {
    foo;

    constructor(public bar){
        this.foo = bar;
    }
}
@QuinntyneBrown
Copy link

1st option and maybe I would express my intentions a little better with a getter. If foo is a computed property or is pointing at something else, I would probably do "get foo() { return this.bar; }"

@jevenson
Copy link

2nd option IMO. Still weird, but 2nd option reads easier.

@vsavkin
Copy link

vsavkin commented Mar 17, 2016

I prefer the first option.

  • I don't have repeat 'foo' twice
  • if I have a const initializer, then I always put it next to the field declaration. And it is nice to have all my initializers in the same place.

@ajoslin
Copy link

ajoslin commented Mar 17, 2016

(2) because it's more clear what's happening. To someone from Javascript, the "this" in example (1) looks like the global scope, and it looks like a programming error.

@robertpenner
Copy link

Side issue: does bar have to be public? Will the DI work with constructor(private bar: Bar)?

https://gist.github.com/johnlindquist/5b8a1111cda507ea3d05

@robertpenner
Copy link

I don't like the argument that is essentially "someone who doesn't understand TypeScript won't understand it."

@robertpenner
Copy link

I agree with @vsavkin's points exactly.

@basarat
Copy link

basarat commented Mar 17, 2016

2nd Option. Any code in property initializes actually executes before the body of the constructor. This is great because it allows you to use initialized members in the constructor body e.g.:

export class App {
    foo = [];
    constructor(public bar){
        this.foo.push(bar); // Safe to do
    }
}

So if you use the 1st option, it might not do what you think it does. e.g. What do you think is the value of foo in this case?

export class App {
    foo = this.bar;
    constructor(public bar){
        bar = bar * 2;
    }
}

Whereas with the following case there is no ambiguity:

export class App {
    foo;
    constructor(public bar){
        this.foo = bar * 2;
    }
}

I know the example is a bit contrived 🌹

@mithun-daa
Copy link

Option 2 seems intuitive to me and I also agree with @basarat 's points

@jeffwhelpley
Copy link

Option 2...but why wouldn't you just use this.bar and get rid of foo altogether?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment