Skip to content

Commit 70f29fa

Browse files
Merge pull request #254 from SarahIsWeird/main
Fix references to `this` in default arguments of class/object methods
2 parents 4b82bec + b0ba71f commit 70f29fa

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
export default ({ expect }: typeof import('vitest')) => {
2+
class Foo {
3+
declare foo: number
4+
5+
constructor() {
6+
this.foo = 1
7+
}
8+
9+
bar() {
10+
return 2
11+
}
12+
13+
baz(a = this.foo, b = this.bar()) {
14+
return a + b
15+
}
16+
}
17+
18+
const obj = {
19+
foo: 1,
20+
bar() {
21+
return 2
22+
},
23+
baz(a = this.foo, b = this.bar()) {
24+
return a + b
25+
}
26+
}
27+
28+
const foo = (new Foo)
29+
30+
expect(foo.baz(3, 4)).toBe(7) // Is this the real life?
31+
expect(foo.baz()).toBe(3) // Is this just fantasy?
32+
33+
expect(obj.baz(3, 4)).toBe(7) // Caught in a landslide
34+
expect(obj.baz()).toBe(3) // No escape from reality
35+
}

src/processScript/transform.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -821,6 +821,19 @@ export function transform(
821821

822822
let methodReferencesThis = false as boolean
823823

824+
for (const param of classMethod.params) {
825+
traverse(param, {
826+
ThisExpression(path) {
827+
// We can't reference _abc_THIS_ here, because there would be
828+
// nowhere to place the assignment to that!
829+
// Hence, we just do the super thing directly.
830+
path.replaceWith(t.callExpression(
831+
t.memberExpression(t.super(), t.identifier(`valueOf`)), []
832+
))
833+
}
834+
}, scope)
835+
}
836+
824837
traverse(classMethod.body, {
825838
ThisExpression(path) {
826839
methodReferencesThis = true

0 commit comments

Comments
 (0)