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

Enumerating through class instance properties prior to construct #51

Closed kirkouimet closed 8 years ago

kirkouimet commented 8 years ago

Does this proposal allow me to enumerate through the properties of an instance of a class without instantiating it?

Let's say I have a class like this:

class Person {
    firstName = null;
    lastName = null;

    construct() {
        console.log('Hi!');
    }
}

I want to be able to know, without doing new Person() that the Person class has the properties firstName and lastName and what their default values are. The current way that Babel is transpiling this class is like this:

var Person = function () {
    function Person() {
        _classCallCheck(this, Person);

        this.firstName = null;
        this.lastName = null;
    }

    Person.prototype.construct = function construct() {
        console.log('Hi!');
    };

    return Person;
}();

Because the assignments are done in the constructor, I have no insight into what properties will exist on the class until a class instance is instantiated. It would be super useful for the code to be transpiled like this:

var Person = function () {
    function Person() {
        _classCallCheck(this, Person);
    }

    Person.prototype.firstName = null;
    Person.prototype.lastName = null;

    Person.prototype.construct = function construct() {
        console.log('Hi!');
    };

    return Person;
}();

Knowing what properties a class instance has prior to instantiating it is quite useful when writing reflection code.

ljharb commented 8 years ago

Without this proposal, you wouldn't be able to do that, since it'd just be properties set in the constructor. Typically if you want instance properties visible via reflection on the prototype,', you assign prototypical default values on the prototype that the constructor then shadows.

jeffmo commented 8 years ago

@ljharb is correct that it's not possible in the proposal as-is. There was discussion early on about adding a reflection API that would allow you to extract the fields/some descriptor(s) of the fields on a class object.

That API likely won't make it in to this proposal (need to make progress, so need to limit feature creep), but there should be nothing that prevents such a thing from being proposed and introduced later. I think such an API would be worth exploring.