Skip to content

Commit

Permalink
feat: update class-methods-use-this for class static blocks (#15298)
Browse files Browse the repository at this point in the history
Updates the `class-methods-use-this` rule to account for class static blocks.

This only fixes false negatives where use of `this` in a class static block mistakenly counts as used `this` in the enclosing context.

The rule still correctly does not require that class static blocks use `this`.

Refs #15016
  • Loading branch information
mdjermanovic committed Nov 15, 2021
1 parent cdaa541 commit d3a267f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
4 changes: 4 additions & 0 deletions docs/rules/class-methods-use-this.md
Expand Up @@ -83,6 +83,10 @@ class A {
static foo() {
// OK. static methods aren't expected to use this.
}

static {
// OK. static blocks are exempt.
}
}
```

Expand Down
11 changes: 10 additions & 1 deletion lib/rules/class-methods-use-this.js
Expand Up @@ -161,8 +161,17 @@ module.exports = {
/*
* Class field value are implicit functions.
*/
"PropertyDefinition:exit": popContext,
"PropertyDefinition > *.key:exit": pushContext,
"PropertyDefinition:exit": popContext,

/*
* Class static blocks are implicit functions. They aren't required to use `this`,
* but we have to push context so that it captures any use of `this` in the static block
* separately from enclosing contexts, because static blocks have their own `this` and it
* shouldn't count as used `this` in enclosing contexts.
*/
StaticBlock: pushContext,
"StaticBlock:exit": popContext,

ThisExpression: markThisUsed,
Super: markThisUsed,
Expand Down
10 changes: 9 additions & 1 deletion tests/lib/rules/class-methods-use-this.js
Expand Up @@ -41,7 +41,8 @@ ruleTester.run("class-methods-use-this", rule, {
{ code: "class A { #bar() {} }", options: [{ exceptMethods: ["#bar"] }], parserOptions: { ecmaVersion: 2022 } },
{ code: "class A { foo = function () {} }", options: [{ enforceForClassFields: false }], parserOptions: { ecmaVersion: 2022 } },
{ code: "class A { foo = () => {} }", options: [{ enforceForClassFields: false }], parserOptions: { ecmaVersion: 2022 } },
{ code: "class A { foo() { return class { [this.foo] = 1 }; } }", parserOptions: { ecmaVersion: 2022 } }
{ code: "class A { foo() { return class { [this.foo] = 1 }; } }", parserOptions: { ecmaVersion: 2022 } },
{ code: "class A { static {} }", parserOptions: { ecmaVersion: 2022 } }
],
invalid: [
{
Expand Down Expand Up @@ -203,6 +204,13 @@ ruleTester.run("class-methods-use-this", rule, {
errors: [
{ messageId: "missingThis", data: { name: "method 'foo'" }, column: 11, endColumn: 15 }
]
},
{
code: "class A { foo () { return class { static { this; } } } }",
parserOptions: { ecmaVersion: 2022 },
errors: [
{ messageId: "missingThis", data: { name: "method 'foo'" }, column: 11, endColumn: 15 }
]
}
]
});

0 comments on commit d3a267f

Please sign in to comment.