fix: allow to access private fields after `this` reassignment (#11487)

Fixes #11480
Fixes #11476
pull/11474/head
Paolo Ricciuti 8 months ago committed by GitHub
parent 0d5a32d5f7
commit fa3e98e8c6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
"svelte": patch
---
fix: allow to access private fields after `this` reassignment

@ -13,15 +13,13 @@ export const global_visitors = {
} }
}, },
MemberExpression(node, { state, next }) { MemberExpression(node, { state, next }) {
if (node.object.type === 'ThisExpression') { // rewrite `this.#foo` as `this.#foo.v` inside a constructor
// rewrite `this.#foo` as `this.#foo.v` inside a constructor if (node.property.type === 'PrivateIdentifier') {
if (node.property.type === 'PrivateIdentifier') { const field = state.private_state.get(node.property.name);
const field = state.private_state.get(node.property.name); if (field) {
if (field) { return state.in_constructor ? b.member(node, b.id('v')) : b.call('$.get', node);
return state.in_constructor ? b.member(node, b.id('v')) : b.call('$.get', node);
}
} }
} else if (node.object.type === 'ThisExpression') {
// rewrite `this.foo` as `this.#foo.v` inside a constructor // rewrite `this.foo` as `this.#foo.v` inside a constructor
if (node.property.type === 'Identifier' && !node.computed) { if (node.property.type === 'Identifier' && !node.computed) {
const field = state.public_state.get(node.property.name); const field = state.public_state.get(node.property.name);

@ -0,0 +1,10 @@
import { test } from '../../test';
export default test({
compileOptions: {
dev: true
},
async test({ assert, logs }) {
assert.deepEqual(logs, ['init', 1, 'init', 1]);
}
});

@ -0,0 +1,23 @@
<script>
class Counter {
#count = $state();
constructor(){
const instance = this;
instance.#count = 1;
}
get count(){
return this.#count;
}
get count2() {
const instance = this;
return instance.#count;
}
}
const counter = new Counter();
$inspect(counter.count)
$inspect(counter.count2)
</script>
Loading…
Cancel
Save