49 lines
2.7 KiB
Plaintext
49 lines
2.7 KiB
Plaintext
== Why is this an issue?
|
|
|
|
If the function call can be written in a normal way, then calling that function with `.call()` or `.apply()` methods is redundant and can be removed without affecting the behavior of the code.
|
|
|
|
The `.call()` and `.apply()` methods are traditionally used to explicitely set the value of `this` keyword when executing a function or an object method. When calling a method of an object the value of `this` by default will be the reference to that object. But if you call a function or a method using `.call()` and `.apply()` you can set the value of `this` to any object, whatever you put into the first argument.
|
|
|
|
[source,javascript]
|
|
----
|
|
let obj = {
|
|
checkThis() {
|
|
this === obj; // true, if called the normal way: obj.checkThis()
|
|
}
|
|
};
|
|
|
|
let otherObject = {};
|
|
|
|
obj.checkThis.call(otherObject); // this === otherObject, if called this way
|
|
----
|
|
|
|
There is also a special case when your code is not in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode[strict mode] and the first argument to the `.call()` and `.apply()` methods is `null` or `undefined`. In this case the value of `this` is substituted with the `globalThis` object, usually `window` when in browser context, and it make such call equivalent to just calling the function the normal way.
|
|
|
|
So if you are calling a function using `.call()` or `.apply()` methods and the first argument is `null` or `undefined`, or you are calling an object method and the first argument is the object itself, then `.call()` or `.apply()` methods become redundant, and should be removed to make the code more simple and easier to understand.
|
|
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
foo.call(null, 1, 2); // Noncompliant: .call() is redundant
|
|
obj.foo.call(obj, arg1, arg2); // Noncompliant: .call() is redundant
|
|
bar.apply(undefined, [x, y, z]); // Noncompliant: .apply() is redundant
|
|
----
|
|
|
|
To fix your code remove redundant `.call()` or `.apply()` methods.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
foo(1, 2);
|
|
obj.foo(arg1, arg2);
|
|
bar(x, y, z);
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions[Functions]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call[Function.prototype.call()]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply[Function.prototype.apply()]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this[this]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis[globalThis]
|