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.
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 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.
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.
foo(1, 2);
obj.foo(arg1, arg2);
bar(x, y, z);