1 | # `no-this-alias`
|
2 |
|
3 | Disallow aliasing `this`.
|
4 |
|
5 | This rule prohibits assigning variables to `this`.
|
6 |
|
7 | ## Rule Details
|
8 |
|
9 | Rationale from TSLint:
|
10 |
|
11 | > Assigning a variable to `this` instead of properly using arrow lambdas may be a symptom of pre-ES6 practices
|
12 | > or not managing scope well.
|
13 | >
|
14 | > Instead of storing a reference to `this` and using it inside a `function () {`:
|
15 | >
|
16 | > ```js
|
17 | > const self = this;
|
18 | >
|
19 | > setTimeout(function () {
|
20 | > self.doWork();
|
21 | > });
|
22 | > ```
|
23 | >
|
24 | > Use `() =>` arrow lambdas, as they preserve `this` scope for you:
|
25 | >
|
26 | > ```js
|
27 | > setTimeout(() => {
|
28 | > this.doWork();
|
29 | > });
|
30 | > ```
|
31 |
|
32 | Examples of **incorrect** code for this rule:
|
33 |
|
34 | (see the rationale above)
|
35 |
|
36 | Examples of **correct** code for this rule:
|
37 |
|
38 | (see the rationale above)
|
39 |
|
40 | ## Options
|
41 |
|
42 | You can pass an object option:
|
43 |
|
44 | ```jsonc
|
45 | {
|
46 | "@typescript-eslint/no-this-alias": [
|
47 | "error",
|
48 | {
|
49 | "allowDestructuring": false, // Disallow `const { props, state } = this`; true by default
|
50 | "allowedNames": ["self"] // Allow `const self = this`; `[]` by default
|
51 | }
|
52 | ]
|
53 | }
|
54 | ```
|
55 |
|
56 | ## When Not To Use It
|
57 |
|
58 | If you need to assign `this` to variables, you shouldn’t use this rule.
|
59 |
|
60 | ## Related To
|
61 |
|
62 | - TSLint: [`no-this-assignment`](https://palantir.github.io/tslint/rules/no-this-assignment/)
|
63 |
|
64 | ## Attributes
|
65 |
|
66 | - Configs:
|
67 | - [x] ✅ Recommended
|
68 | - [x] 🔒 Strict
|
69 | - [ ] 🔧 Fixable
|
70 | - [ ] 💭 Requires type information
|