Skip to content

Commit fa3e98e

Browse files
fix: allow to access private fields after this reassignment (#11487)
Fixes #11480 Fixes #11476
1 parent 0d5a32d commit fa3e98e

File tree

4 files changed

+44
-8
lines changed

4 files changed

+44
-8
lines changed

.changeset/gentle-toys-chew.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"svelte": patch
3+
---
4+
5+
fix: allow to access private fields after `this` reassignment

packages/svelte/src/compiler/phases/3-transform/client/visitors/global.js

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,13 @@ export const global_visitors = {
1313
}
1414
},
1515
MemberExpression(node, { state, next }) {
16-
if (node.object.type === 'ThisExpression') {
17-
// rewrite `this.#foo` as `this.#foo.v` inside a constructor
18-
if (node.property.type === 'PrivateIdentifier') {
19-
const field = state.private_state.get(node.property.name);
20-
if (field) {
21-
return state.in_constructor ? b.member(node, b.id('v')) : b.call('$.get', node);
22-
}
16+
// rewrite `this.#foo` as `this.#foo.v` inside a constructor
17+
if (node.property.type === 'PrivateIdentifier') {
18+
const field = state.private_state.get(node.property.name);
19+
if (field) {
20+
return state.in_constructor ? b.member(node, b.id('v')) : b.call('$.get', node);
2321
}
24-
22+
} else if (node.object.type === 'ThisExpression') {
2523
// rewrite `this.foo` as `this.#foo.v` inside a constructor
2624
if (node.property.type === 'Identifier' && !node.computed) {
2725
const field = state.public_state.get(node.property.name);
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { test } from '../../test';
2+
3+
export default test({
4+
compileOptions: {
5+
dev: true
6+
},
7+
async test({ assert, logs }) {
8+
assert.deepEqual(logs, ['init', 1, 'init', 1]);
9+
}
10+
});
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<script>
2+
class Counter {
3+
#count = $state();
4+
5+
constructor(){
6+
const instance = this;
7+
instance.#count = 1;
8+
}
9+
10+
get count(){
11+
return this.#count;
12+
}
13+
14+
get count2() {
15+
const instance = this;
16+
return instance.#count;
17+
}
18+
}
19+
const counter = new Counter();
20+
21+
$inspect(counter.count)
22+
$inspect(counter.count2)
23+
</script>

0 commit comments

Comments
 (0)