]>
Commit | Line | Data |
---|---|---|
eb39fafa DC |
1 | # Disallow unnecessary `.call()` and `.apply()`. (no-useless-call) |
2 | ||
3 | The function invocation can be written by `Function.prototype.call()` and `Function.prototype.apply()`. | |
4 | But `Function.prototype.call()` and `Function.prototype.apply()` are slower than the normal function invocation. | |
5 | ||
6 | ## Rule Details | |
7 | ||
8 | This rule is aimed to flag usage of `Function.prototype.call()` and `Function.prototype.apply()` that can be replaced with the normal function invocation. | |
9 | ||
10 | Examples of **incorrect** code for this rule: | |
11 | ||
12 | ```js | |
13 | /*eslint no-useless-call: "error"*/ | |
14 | ||
15 | // These are same as `foo(1, 2, 3);` | |
16 | foo.call(undefined, 1, 2, 3); | |
17 | foo.apply(undefined, [1, 2, 3]); | |
18 | foo.call(null, 1, 2, 3); | |
19 | foo.apply(null, [1, 2, 3]); | |
20 | ||
21 | // These are same as `obj.foo(1, 2, 3);` | |
22 | obj.foo.call(obj, 1, 2, 3); | |
23 | obj.foo.apply(obj, [1, 2, 3]); | |
24 | ``` | |
25 | ||
26 | Examples of **correct** code for this rule: | |
27 | ||
28 | ```js | |
29 | /*eslint no-useless-call: "error"*/ | |
30 | ||
31 | // The `this` binding is different. | |
32 | foo.call(obj, 1, 2, 3); | |
33 | foo.apply(obj, [1, 2, 3]); | |
34 | obj.foo.call(null, 1, 2, 3); | |
35 | obj.foo.apply(null, [1, 2, 3]); | |
36 | obj.foo.call(otherObj, 1, 2, 3); | |
37 | obj.foo.apply(otherObj, [1, 2, 3]); | |
38 | ||
39 | // The argument list is variadic. | |
40 | // Those are warned by the `prefer-spread` rule. | |
41 | foo.apply(undefined, args); | |
42 | foo.apply(null, args); | |
43 | obj.foo.apply(obj, args); | |
44 | ``` | |
45 | ||
46 | ## Known Limitations | |
47 | ||
48 | This rule compares code statically to check whether or not `thisArg` is changed. | |
49 | So if the code about `thisArg` is a dynamic expression, this rule cannot judge correctly. | |
50 | ||
51 | Examples of **incorrect** code for this rule: | |
52 | ||
53 | ```js | |
54 | /*eslint no-useless-call: "error"*/ | |
55 | ||
56 | a[i++].foo.call(a[i++], 1, 2, 3); | |
57 | ``` | |
58 | ||
59 | Examples of **correct** code for this rule: | |
60 | ||
61 | ```js | |
62 | /*eslint no-useless-call: "error"*/ | |
63 | ||
64 | a[++i].foo.call(a[i], 1, 2, 3); | |
65 | ``` | |
66 | ||
67 | ## When Not To Use It | |
68 | ||
69 | If you don't want to be notified about unnecessary `.call()` and `.apply()`, you can safely disable this rule. | |
70 | ||
71 | ## Related Rules | |
72 | ||
73 | * [prefer-spread](prefer-spread.md) |