no-invalid-this
UnreleasedConfiguration
Rule Details
Under strict mode, this keywords outside of classes or class-like objects might be undefined and raise a TypeError. This rule applies only in strict mode; sloppy-mode code (a plain script with no "use strict" directive and no ES module syntax) is never flagged.
Top-level this at the top of a script always refers to the global object and is valid. Top-level this in an ES module is always invalid, since its value is undefined.
For this inside functions, 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)).
And this rule always allows this keywords in the following contexts:
- At the top level of scripts.
- In class field initializers.
- In class static blocks.
Otherwise, this rule warns on this keywords.
Examples of incorrect code for this rule in strict mode:
Examples of correct code for this rule in strict mode:
Options
This rule has an object option, with one option:
"capIsConstructor": false(defaulttrue) disables the assumption that a function whose name starts with an uppercase letter is a constructor.
capIsConstructor
By default, this rule always allows the use of this in functions whose name starts with an uppercase letter and anonymous functions that are assigned to a variable whose name starts with an uppercase letter, assuming that those functions are used as constructor functions.
Set "capIsConstructor" to false if you want those functions to be treated as regular functions.
Examples of incorrect code for this rule with { "capIsConstructor": false }:
Examples of correct code for this rule with { "capIsConstructor": false }:
Differences from ESLint
- rslint does not expose ESLint's legacy
parserOptions.ecmaFeatures.globalReturnescape hatch.
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.