tc39 / proposal-class-public-fields

Stage 2 proposal for public class fields in ECMAScript
https://tc39.github.io/proposal-class-public-fields/
488 stars 25 forks source link

Confusion with "this" and computed properties. #23

Closed ljharb closed 8 years ago

ljharb commented 8 years ago

What would:

this.foo = 'a';
class Foo {
  foo = 'b';
  [this.foo] = this.foo;
}

produce? An "a" property or a "b" property? An "a" value or a "b" value?

My guess based on my understanding of the spec is that it'd be an "a" property with a "b" value, but I wanted to confirm.

jeffmo commented 8 years ago

Given the current spec, "An 'a' property with a 'b' value" is correct.

This is also highly irregular code, so while it's an interesting oddity -- it's not clear how much it should weigh against the usefulness of having access to this in an initializer position.

The RHS of the initializer is an expression that is deferred until construction time, so it's possible to draw examples where anything it evaluates (this or otherwise) aren't what you might expect if you didn't understand how this works.

jeffmo commented 8 years ago

(Closing, but feel free to re-open if there's anything else actionable here)

ljharb commented 8 years ago

Nope, just wanted to point it out (the other computed property issues didn't have this case) and make sure I understood it correctly.

The only part I think this makes a bit confusing is that it no longer is the same thing as "cut and paste the initializer lines into the constructor after the super call", since any computed property names have to be evaluated in the same context as the "class" itself, before dumping the lines into the constructor - ie, the mental model is a bit trickier there, even though I understand how it works using a property descriptor.

jeffmo commented 8 years ago

The only part I think this makes a bit confusing is that it no longer is the same thing as "cut and paste the initializer lines into the constructor after the super call"

Yea, that is an interesting point I hadn't considered. I suppose this holds for any computed property expression given deferred evaluation of the RHS.