Function.prototype.call() should not be used when this context remains the same

  • USELESS_CALL
  • Code Quality
  • Low
  • No tags

This rule applies when this context remains the same after applying Function.prototype.call().

When an object method is called, its this context is normally set to the object on which it is called.
This behavior can be changed by invoking the method through Function.prototype.call().

However, when Function.prototype.call() does not change this context, it becomes useless. For example, obj.foo.call(obj, 42) is equivalent to obj.foo(42).
This could happen as a result of refactoring or could be an actual bug. So, it is recommended to check the code and remove Function.prototype.call() if it is not needed.

This rule also applies to Function.prototype.apply() when the number of argument is 1.

Noncompliant Code Example

View with compliant examples side by side
class Test {
    data = 'data';
    foo() {
        console.log(this.data);
    }
    bar() {
        this.foo.call(this); // USELESS_CALL alarm
    }
}

Compliant Code Example

View with noncompliant examples side by side
class Test {
    data = 'data';
    foo() {
        console.log(this.data);
    }
    bar() {
        this.foo();
    }
}

Version

This rule was introduced in DeepScan 1.26.0.

See

Was this documentation helpful?