Skip to content

Commit 5661fa6

Browse files
authored
feat: no-extra-bind false negatives with class fields and static blocks (#21260)
* fix: no-extra-bind should flag unnecessary bind with class fields/static blocks * apply review suggestions
1 parent 007e81a commit 5661fa6

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

‎lib/rules/no-extra-bind.js‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,16 @@ module.exports = {
218218
"FunctionDeclaration:exit": exitFunction,
219219
FunctionExpression: enterFunction,
220220
"FunctionExpression:exit": exitFunction,
221+
222+
/*
223+
* Class field initializers and static blocks have their own `this` binding.
224+
* Enter the scope after the key, which is evaluated in the enclosing scope.
225+
*/
226+
"PropertyDefinition > *.key:exit": enterFunction,
227+
"PropertyDefinition:exit": exitFunction,
228+
StaticBlock: enterFunction,
229+
"StaticBlock:exit": exitFunction,
230+
221231
ThisExpression: markAsThisFound,
222232
};
223233
},

‎tests/lib/rules/no-extra-bind.js‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,20 @@ ruleTester.run("no-extra-bind", rule, {
4747
code: "var a = function() { return () => this; }.bind(b)",
4848
languageOptions: { ecmaVersion: 6 },
4949
},
50+
51+
// Class fields and static blocks
52+
{
53+
code: "var a = function() { return class { [this.foo] = 5; }; }.bind(b);",
54+
languageOptions: { ecmaVersion: 2022 },
55+
},
56+
{
57+
code: "class C { field = function() { this; }.bind(b); }",
58+
languageOptions: { ecmaVersion: 2022 },
59+
},
60+
{
61+
code: "class C { static { var a = function() { this; }.bind(b); } }",
62+
languageOptions: { ecmaVersion: 2022 },
63+
},
5064
],
5165
invalid: [
5266
{
@@ -253,5 +267,25 @@ ruleTester.run("no-extra-bind", rule, {
253267
languageOptions: { ecmaVersion: 2020 },
254268
errors: [{ messageId: "unexpected" }],
255269
},
270+
271+
// Class fields and static blocks
272+
{
273+
code: "var a = function() { class C { field = this.x; } }.bind(b)",
274+
output: "var a = function() { class C { field = this.x; } }",
275+
languageOptions: { ecmaVersion: 2022 },
276+
errors,
277+
},
278+
{
279+
code: "var a = function() { class C { static field = this.x; } }.bind(b)",
280+
output: "var a = function() { class C { static field = this.x; } }",
281+
languageOptions: { ecmaVersion: 2022 },
282+
errors,
283+
},
284+
{
285+
code: "var a = function() { class C { static { this.x = 1; } } }.bind(b)",
286+
output: "var a = function() { class C { static { this.x = 1; } } }",
287+
languageOptions: { ecmaVersion: 2022 },
288+
errors,
289+
},
256290
],
257291
});

0 commit comments

Comments
 (0)