47 lines
1.2 KiB
Plaintext
47 lines
1.2 KiB
Plaintext
Unnecessary calls to `.bind()` should not be used.
|
|
|
|
== Why is this an issue?
|
|
|
|
The `.bind()` method allows specifying the value of `this` and, optionally, the values of some function arguments. However, if `this` is not used in the function body, calls to `.bind()` do nothing and should be removed.
|
|
|
|
Calling `.bind()` on arrow functions is a bug because the value of `this` does not change when `.bind()` is applied to arrow functions.
|
|
|
|
== How to fix it
|
|
|
|
Remove calls to `.bind()` method.
|
|
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
let x = function fn() {
|
|
return 123;
|
|
}.bind({value: 456}); // Noncompliant
|
|
|
|
|
|
let y = (() => this.body).bind(document); // Noncompliant
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
let x = (function callback() {
|
|
return this.body;
|
|
}).bind(document); // ok, not an arrow function
|
|
|
|
|
|
let y = (function print(x) {
|
|
console.log(x);
|
|
}).bind(this, foo); // ok, binds argument
|
|
----
|
|
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind[``++Function.prototype.bind()++``]
|