1 # Disallow unnecessary function binding (no-extra-bind)
3 The `bind()` method is used to create functions with specific `this` values and, optionally, binds arguments to specific values. When used to specify the value of `this`, it's important that the function actually uses `this` in its function body. For example:
6 var boundGetName = (function getName() {
8 }).bind({ name: "ESLint" });
10 console.log(boundGetName()); // "ESLint"
13 This code is an example of a good use of `bind()` for setting the value of `this`.
15 Sometimes during the course of code maintenance, the `this` value is removed from the function body. In that case, you can end up with a call to `bind()` that doesn't accomplish anything:
19 var boundGetName = (function getName() {
21 }).bind({ name: "ESLint" });
23 console.log(boundGetName()); // "ESLint"
26 In this code, the reference to `this` has been removed but `bind()` is still used. In this case, the `bind()` is unnecessary overhead (and a performance hit) and can be safely removed.
30 This rule is aimed at avoiding the unnecessary use of `bind()` and as such will warn whenever an immediately-invoked function expression (IIFE) is using `bind()` and doesn't have an appropriate `this` value. This rule won't flag usage of `bind()` that includes function argument binding.
32 **Note:** Arrow functions can never have their `this` value set using `bind()`. This rule flags all uses of `bind()` with arrow functions as a problem
34 Examples of **incorrect** code for this rule:
37 /*eslint no-extra-bind: "error"*/
65 Examples of **correct** code for this rule:
68 /*eslint no-extra-bind: "error"*/
74 var x = function (a) {
81 If you are not concerned about unnecessary calls to `bind()`, you can safely disable this rule.
85 * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)
86 * [Understanding JavaScript's Function.prototype.bind](https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/)