diff --git a/game-scripts-tests/this_in_default_argument.ts b/game-scripts-tests/this_in_default_argument.ts new file mode 100644 index 0000000..f903b3e --- /dev/null +++ b/game-scripts-tests/this_in_default_argument.ts @@ -0,0 +1,35 @@ +export default ({ expect }: typeof import('vitest')) => { + class Foo { + declare foo: number + + constructor() { + this.foo = 1 + } + + bar() { + return 2 + } + + baz(a = this.foo, b = this.bar()) { + return a + b + } + } + + const obj = { + foo: 1, + bar() { + return 2 + }, + baz(a = this.foo, b = this.bar()) { + return a + b + } + } + + const foo = (new Foo) + + expect(foo.baz(3, 4)).toBe(7) // Is this the real life? + expect(foo.baz()).toBe(3) // Is this just fantasy? + + expect(obj.baz(3, 4)).toBe(7) // Caught in a landslide + expect(obj.baz()).toBe(3) // No escape from reality +} diff --git a/src/processScript/transform.ts b/src/processScript/transform.ts index 16776e3..609f020 100644 --- a/src/processScript/transform.ts +++ b/src/processScript/transform.ts @@ -821,6 +821,19 @@ export function transform( let methodReferencesThis = false as boolean + for (const param of classMethod.params) { + traverse(param, { + ThisExpression(path) { + // We can't reference _abc_THIS_ here, because there would be + // nowhere to place the assignment to that! + // Hence, we just do the super thing directly. + path.replaceWith(t.callExpression( + t.memberExpression(t.super(), t.identifier(`valueOf`)), [] + )) + } + }, scope) + } + traverse(classMethod.body, { ThisExpression(path) { methodReferencesThis = true