no-invalid-this
Configuration
Disallow this keywords outside of classes or class-like objects.
Rule Details
Under strict mode, this keywords outside of classes or class-like objects might be undefined and raise a TypeError.
This rule judges from the following conditions whether or not the function is a constructor:
- The name of the function starts with uppercase.
- The function is assigned to a variable which starts with an uppercase letter.
- The function is a constructor of ES2015 Classes.
This rule judges from the following conditions whether or not the function is a method:
- The function is on an object literal.
- The function is assigned to a property.
- The function is a method / getter / setter of ES2015 Classes.
And this rule allows this keywords in functions below:
- The
call/apply/bindmethod of the function is called directly. - The function is a callback of array methods (such as
.forEach()) ifthisArgis given. - The function has an
@thistag in its JSDoc comment. - The function declares an explicit
thisparameter (function foo(this: SomeType)).
Otherwise, this rule warns on this keywords. It also reports this at the top level.
Examples of incorrect code for this rule:
Examples of correct code for this rule:
Options
capIsConstructor
Type: boolean — Default: true
When true, the rule treats a function whose name starts with an uppercase letter (or which is assigned to such a variable) as an ES5 constructor — this inside is allowed. Set this option to false to treat capitalized-name functions as regular functions.
Examples of incorrect code with { "capIsConstructor": false }:
Examples of correct code with { "capIsConstructor": false }:
When Not To Use It
If you do not want to be notified about usage of the this keyword outside of classes or class-like objects, you can safely disable this rule.