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

about react use case #17

Closed ustccjw closed 9 years ago

ustccjw commented 9 years ago

In React es6 classes, we want autoBinding, we can do:

class Foo extends React.Component {
  render() {
    // ...
  }
  handleChange = (e) => {
    // ...
  }
}

But handleChange is instance field, how we can defined prototype field in class.

jeffmo commented 9 years ago

This proposal does not include support for prototype fields. Instance fields represent an own-property that is created on all instances of a class.

This is analogous to the idiomatic way to initialize class properties today:

class Foo extends React.Component {
  constructor(...args) {
    super(...args);

    this.handleChange = (e) => {
      // ...
    };
  }
}
jeffmo commented 9 years ago

Can you go in to more detail about why you need the field to sit on the prototype rather than the instance?

ustccjw commented 9 years ago

handleChange is a method of instance, in OO, instance method is shared by all instances. So I need the field to set on prototype.

jeffmo commented 9 years ago

The only way to observe the difference between this field sitting on a shared prototype and it sitting on each instance is if you are mutating the function object itself after instantiation. I don't think you're looking to do that, though (correct me if I'm wrong here).

If you don't in fact mutate this field, it's even plausible that VMs can even optimize this if it becomes worthwhile to do so.

I don't think putting this field on the prototype is actually giving you anything.

ustccjw commented 9 years ago

Thanks, i get it. This example may be special.

But if i really need a variable to set on prototype, how should i do in Class?

jeffmo commented 9 years ago

You can always resort to the imperative style of mutating the prototype after the class definition, or you could write a decorator to set on the prototype rather than instance using the pending decorators proposal:

class Foo { @protoify protoProp = () => ... }

ustccjw commented 9 years ago

Thanks!