On Fri, Nov 30, 2018 at 1:52 PM Simo Costa
<[email protected]> wrote:
>
> There is still a repetition, but it is a a step forward.
Yeah. :-| For me, for public properties, it's good enough, but I hear you.
It's a lot of repetition for private fields, though.
Just FWIW by way of prior art, it's probably worth noting TypeScript's
approach, though I'm fairly certain it won't be adopted by JavaScript:
```typescript
class Example {
constructor(
public foo: string,
private bar: number
) {
}
showFoo() {
console.log(e1.foo);
}
showBar() {
console.log(e1.bar);
}
}
const e1 = new Example("answer", 42);
e1.showFoo(); // "answer"
e1.showBar(); // 42
```
The `public` and `private` in the parameter list both declare them as
members of the type and auto-initialize them from the parameters. (That
`private` is TypeScript's version of private, not JavaScript's -- the
member is not part of the type's public interface, just its private one, so
the TypeScript compiler can error on inappropriate use, but the transpiled
JavaScript has them as normal properties.)
The equivalent (but with real private fields) with the [class fields
proposal][1] would be:
```typescript
class Example {
foo;
#bar;
constructor(foo, bar) {
this.foo = foo;
this.#bar = bar;
}
showFoo() {
console.log(e1.foo);
}
showBar() {
console.log(e1.#bar);
}
}
const e1 = new Example("answer", 42);
e1.showFoo(); // "answer"
e1.showBar(); // 42
```
So, that's typing `foo` and `bar` four types rather than once (in
TypeScript). (Okay, we could have skipped the `foo` declaration and only
typed `foo` three times; but you have to declare private fields, so it's
four for `#bar`/`bar`.)
Continuing the train of thought and taking inspiration from TypeScript
**and** Bob's proposal, this could be a follow-on if Bob's progresses
(which I'd very much like to see):
```js
class Example {
constructor(this.{foo, #bar}) {
}
showFoo() {
console.log(e1.foo);
}
showBar() {
console.log(e1.#bar);
}
}
const e1 = new Example("answer", 42);
e1.showFoo(); // "answer"
e1.showBar(); // 42
```
That construct would both declare (if not already declared) and initialize.
You could repeat it as necessary. For instance, if your constructor
*really* needs a non-property as its first and fourth parameters and
properties/fields as its second, third, and fifth:
```js
class Example {
constructor(first, this.{second, #third}, fourth, this.{fifth}) {
// presumably code here uses `first` and `fourth`
}
}
```
which is
```js
class Example {
second;
#third;
fifth;
constructor(first, this.{second, #third}, fourth, this.{fifth}) {
this.second = second;
this.#third = third;
this.fifth = fifth;
// presumably code here uses `first` and `fourth`
}
}
```
Not a parameter list I'd design without a really, really good reason, but...
Food for thought.
-- T.J. Crowder
[1]: https://github.com/tc39/proposal-class-fields/
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss