]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/consistent-this.md
bump version to 8.4.0-3
[pve-eslint.git] / eslint / docs / rules / consistent-this.md
1 # Require Consistent This (consistent-this)
2
3 It is often necessary to capture the current execution context in order to make it available subsequently. A prominent example of this are jQuery callbacks:
4
5 ```js
6 var that = this;
7 jQuery('li').click(function (event) {
8 // here, "this" is the HTMLElement where the click event occurred
9 that.setFoo(42);
10 });
11 ```
12
13 There are many commonly used aliases for `this` such as `that`, `self` or `me`. It is desirable to ensure that whichever alias the team agrees upon is used consistently throughout the application.
14
15 ## Rule Details
16
17 This rule enforces two things about variables with the designated alias names for `this`:
18
19 * If a variable with a designated name is declared, it *must* be either initialized (in the declaration) or assigned (in the same scope as the declaration) the value `this`.
20 * If a variable is initialized or assigned the value `this`, the name of the variable *must* be a designated alias.
21
22 ## Options
23
24 This rule has one or more string options:
25
26 * designated alias names for `this` (default `"that"`)
27
28 Examples of **incorrect** code for this rule with the default `"that"` option:
29
30 ```js
31 /*eslint consistent-this: ["error", "that"]*/
32
33 var that = 42;
34
35 var self = this;
36
37 that = 42;
38
39 self = this;
40 ```
41
42 Examples of **correct** code for this rule with the default `"that"` option:
43
44 ```js
45 /*eslint consistent-this: ["error", "that"]*/
46
47 var that = this;
48
49 var self = 42;
50
51 var self;
52
53 that = this;
54
55 foo.bar = this;
56 ```
57
58 Examples of **incorrect** code for this rule with the default `"that"` option, if the variable is not initialized:
59
60 ```js
61 /*eslint consistent-this: ["error", "that"]*/
62
63 var that;
64 function f() {
65 that = this;
66 }
67 ```
68
69 Examples of **correct** code for this rule with the default `"that"` option, if the variable is not initialized:
70
71 ```js
72 /*eslint consistent-this: ["error", "that"]*/
73
74 var that;
75 that = this;
76
77 var foo, that;
78 foo = 42;
79 that = this;
80 ```
81
82 ## When Not To Use It
83
84 If you need to capture nested context, `consistent-this` is going to be problematic. Code of that nature is usually difficult to read and maintain and you should consider refactoring it.