Skip to content
This repository has been archived by the owner on Jan 25, 2022. It is now read-only.

Document about the detail of declare a field without an initializer #101

Closed
paranoidjk opened this issue May 12, 2018 · 4 comments
Closed

Comments

@paranoidjk
Copy link

From the readme, i see we can declare a field without an initializer, eg:

class Foo {
  bar;
}

But i am not sure whether if bar will be a instance property or just in prototype? eg:

const FooInstance = new Foo();

Object.getOwnPropertyDescriptor(FooInstance, 'bar'); 
Object.getOwnPropertyDescriptor(Foo.prototype, 'bar'); // undefined?

I am ask because there already have plenty differente behavior, eg:

  • TypeScript class property decorator: in prototype

ref: microsoft/TypeScript#2249

class Foo {
    @F("color")
    @G
    prop: number;
}

// desugars to:

var Foo = (function () {
    function Foo() {
    }
    __decorate([F("color"), G], Foo.prototype, "prop");
    return Foo;
})();
  • @babel/plugin-proposal-class-properties with { "loose": true }: in instance
function Dec(target, key, descriptor) {
    // do nothing
    return descriptor;
}

class Test {
    @Dec
    a;
}

let t = new Test();



console.log(Object.getOwnPropertyDescriptor(t, 'a')); 
/* prints:
{ value: undefined,
  writable: false,
  enumerable: true,
  configurable: false }
*/

ref: babel/babel#7391

@littledan
Copy link
Member

With or without an initializer, it is a property of the instance, not the prototype. For more documentation, see https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html

@paranoidjk
Copy link
Author

OK. Then i guess

class Foo {
  bar; // equal to bar = undefined;
}

will compile to something like:

function Foo() {
  this.bar = undefined;
};

My question if how can i declare a class property in prototype based on this proposal?

What's more, i am ok with this proposal, but i am just worried about the already exist babel or TypeScript code may be broken if we allow declare a field without an initializer.

@littledan
Copy link
Member

This proposal doesn't have any particular support for declaring (non-method) properties on prototypes. You can still do it through modifying the prototype manually, as before.

It's possible that existing Babel/TypeScript code will break, but for many other language features, we've lived through a change in semantics between earlier transpiler versions and fully compliant implementations.

@littledan
Copy link
Member

littledan commented Oct 10, 2018

Let's follow up in microsoft/TypeScript#27644 for the TypeScript compatibility issue. For Babel, the "spec" mode has been compliant in this sense for some time.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants