tc39/proposal-decorators

Are we supposed to be able to access the private field of an accessor?

Closed this issue · 7 comments

Is this supposed to be possible?

class Foo {
	@reactive accessor foo = 123; // creates #foo

	constructor() {
		console.log('Foo instance', this.#foo) // read #foo
	}
}

That code currently doesn't work with Babel proposal-decorators

No, private fields are not accessible syntactically unless they're created syntactically.

Hmm, I'm trying to see what's the practical benefit of accessors if we don't have a syntactical advantage. For example, I was hoping to make a readonly getter like this:

class Foo {
	accessor foo { get; } = 123;

	method() {
		this.#foo = 456
	}
}

but it would have to be something like

class Foo {
	#foo = 123
	
	accessor foo {
		get() {
			return this.#foo
		}
	};

	method() {
		this.#foo = 456
	}
}

which isn't much different than (and actually is longer than)

class Foo {
	#foo = 123
	
	get foo () {
		return this.#foo
	}

	method() {
		this.#foo = 456
	}
}

Are they only for serving the semantics of decorators?

I'd assume the decorator would add the getter and setter automatically, so that @readonly accessor foo = 123; resulted in:

class Foo {
	#foo = 123;
	get foo () {
		return this.#foo;
	}
	set foo() {
		this.#foo;
		throw 'this is readonly' // or whatever
	}
}

I'm not sure how you'd use a decorator to have a private field that's only settable inside the class; i'd indeed just use the output code directly for that.

I see. So return { set() { throw 'readonly' }, ... }. Is there a benefit other than for decorators?

in that case the benefit is that something outside the class can't write to .foo on the instance.

olee commented

So the private fields generated by accessor are not accessible except through the accessor? Ie. in transpilers they would be generated with some random identifier for example?

Correct.