Skip to content

Replace this in function expressions in object properties #257

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions game-scripts-tests/this_in_lambda_in_object.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Since this is the thing being tested, we need to disable the ESLint rule instead.
/* eslint-disable object-shorthand */

export default ({ expect }: typeof import('vitest')) => {
const myObject = {
a: 0,
b: function () {
this.a++
return this.a
},
c: function (value: number = this.a) {
this.a = value + 1
},
d: function ({ value = this.a }: { value?: number }) {
this.a = value + 1
}
}

expect(myObject.a).toBe(0)
myObject.b()
expect(myObject.a).toBe(1)
myObject.c()
expect(myObject.a).toBe(2)
myObject.d({})
expect(myObject.a).toBe(3)
}
13 changes: 11 additions & 2 deletions src/processScript/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -749,10 +749,19 @@ export function transform(

if (object.type == `ObjectExpression`) {
for (const property of (object as ObjectExpression).properties) {
if (property.type != `ObjectMethod`)
if (property.type == `ObjectMethod`) {
thisIsReferenced ||= replaceAllThisWith(property, scope, thisId)
continue
}

if (property.type == `ObjectProperty` && property.value.type == `FunctionExpression`) {
// Replace in things like this: function (foo = this.a)
for (const param of property.value.params) {
thisIsReferenced ||= replaceAllThisWith(param, scope, thisId)
}

thisIsReferenced ||= replaceAllThisWith(property, scope, thisId)
thisIsReferenced ||= replaceAllThisWith(property.value.body, scope, thisId)
}
}
} else {
for (const element of (object as ArrayExpression).elements) {
Expand Down