tc39 / proposal-class-public-fields

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

Examples? #46

Open rwaldron opened 8 years ago

rwaldron commented 8 years ago

Where can I find examples (with explanations) of the syntax in its present state? That seems like something that belongs in this proposal repository eg.

Thanks!

bakkot commented 8 years ago

I've just implemented most of this feature in V8 as an experiment, and am about to write tests from which I can extract some examples to post here.

bakkot commented 8 years ago

These are just to help anyone coming across this before we get more complete examples in the repo.

Basic example:


class Counter {
  count = 0;

  increment() {
    ++this.count;
  }
}

let counter = new Counter;
counter.increment();
console.log(counter.count); // 1

Lots of syntax examples:

// Basic syntax

class C {
  a = 0;
}

class C {
  a;
}

class C {
  static a = 0;
}

class C {
  static a;
}

// ASI examples

class C {
  a = 0
  b(){}
}

class C {
  a
  b
}

class C {
  a
  *b(){}
}

class C {
  a
  ['b'](){}
}

class C { // a property named 'a' and a property named 'get'
  a
  get
}

class C { // a single static property named 'a'
  static
  a
}

class C { // a property named 'a' and a property named 'static'
  a
  static
}

// ASI non-examples / errors

class C { a b } // There is no line terminator after 'a', so ASI does not occur

class C { // '*' may follow 0 in an AssignmentExpression, so no ASI occurs after 0
  a = 0
  *b(){}
}

class C { // '[' may follow 0 in an AssignmentExpression, so no ASI occurs after 0
  a = 0
  ['b'](){}
}

class C { // 'a' may follow 'get' in a MethodDefinition, so no ASI occurs after 'get'
  get
  a
}

// Non-examples

class C { // a getter for 'a' installed on C.prototype; this is existing syntax
  get
  a(){}
}
michaelficarra commented 8 years ago

@bakkot

-class C { // 'a' may follow 0 in a MethodDefinition, so no ASI occurs after 'get'
+class C { // 'a' may follow 'get' in a MethodDefinition, so no ASI occurs after 'get'
Rokt33r commented 7 years ago

Is there any way to get arguments of constructor?

From

class A {
  constructor (opts) {
    this.someProp = opts.someProp
  }
}

let a = new A({someProp: 'Some value'})

To

class A {
  someProp = ???(opts.someProp)
}

let a = new A({someProp: 'Some value'})
bakkot commented 7 years ago

@Rokt33r, not at the moment; see #33 for that general discussion and also https://github.com/sebmarkbage/ecmascript-scoped-constructor-arguments for a proposed fix.

Personally I think that doing the initialization in the constructor is fine, though; that's common enough in other languages, and is more consistent than making constructor arguments available outside their scope.

Rokt33r commented 7 years ago

@bakkot Thanks for the super helpful answer! 💯